In this tutorial, we will learn to convert String to date in java with example.While we working with java this is one of the most scenario
We can easily convert String to Data using SimpleDateFormat.java. But before that we should know the date patterns which mentioned below
Letter | Component | Presentation | Examples |
y | Year | Year | 1996; 96 |
M | Month in year | Month | July; Jul; 07 |
d | Day in month | Number | 10 |
a | Am/pm marker | Text | PM |
H | Hour in day (0-23) | Number | 0 |
k | Hour in day (1-24) | Number | 24 |
K | Hour in am/pm (0-11) | Number | 0 |
h | Hour in am/pm (1-12) | Number | 12 |
m | Minute in hour | Number | 30 |
s | Second in minute | Number | 55 |
S | Millisecond | Number | 978 |
In this example we will convert 20/02/2020 to Date class
Syntax
DateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY");
simpleDateFormat.parse(dateString);
Example
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
try {
String dateString = "20/02/2020";
DateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY");
// Below line will convert from string to date
Date parse = simpleDateFormat.parse(dateString);
// The output will be like Sun Dec 29 00:00:00 IST 2019
System.out.println(" Output :: "+parse);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output
Output :: Sun Dec 29 00:00:00 IST 2019
Reference
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
Download
Related Articles
print current date in java with example
compare two dates in java example