In this example we will show how to convert string to date in Java.
Source Code
1) String = ‘2019-02-26’
package com.beginner.examples;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class String2DateExample1 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str = "2019-02-26";
try
{
Date date = sdf.parse(str);
System.out.println(date);
System.out.println(sdf.format(date));
}
catch (ParseException e)
{
e.printStackTrace();
}
}
}
Output:
Tue Feb 26 00:00:00 UTC 2019
2019-02-26
2) String = ’26/02/2019′
package com.beginner.examples;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class String2DateExample2 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String str = "26/02/2019";
try
{
Date date = sdf.parse(str);
System.out.println(date);
System.out.println(sdf.format(date));
}
catch (ParseException e)
{
e.printStackTrace();
}
}
}
Output:
Tue Feb 26 00:00:00 UTC 2019
2019-02-26
3) String = ’26-February-2019′
package com.beginner.examples;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class String2DateExample3 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
String str = "26-February-2019";
try
{
Date date = sdf.parse(str);
System.out.println(date);
System.out.println(sdf.format(date));
}
catch (ParseException e)
{
e.printStackTrace();
}
}
}
Output:
Tue Feb 26 00:00:00 UTC 2019
2019-02-26
References
Imported packages in Java documentation: