To convert a string to date, Java 8 provides DateTimeFormatter.ofPattern
method in its java.time
package.
package com.techstackjournal;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class StringToDate {
public static void main(String[] args) {
String str1 = "04-18-2020 20:50:30 +05:30";
ZonedDateTime zonedDateTime1 = ZonedDateTime.parse(str1, DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss XXX"));
System.out.println(zonedDateTime1);
String str2 = "04-18-2020 20:50:30 +0530";
ZonedDateTime zonedDateTime2 = ZonedDateTime.parse(str2, DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss ZZ"));
System.out.println(zonedDateTime2);
String str3 = "04-18-2020 20:50:30 -04";
ZonedDateTime zonedDateTime3 = ZonedDateTime.parse(str3, DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss X"));
System.out.println(zonedDateTime3);
String str4 = "04-18-2020 20:50:30 -04:30";
ZonedDateTime zonedDateTime4 = ZonedDateTime.parse(str4, DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss [XXX][ZZ][X]"));
System.out.println(zonedDateTime4);
String str5 = "04-18-2020 20:50:30 America/Montreal";
ZonedDateTime zonedDateTime5 = ZonedDateTime.parse(str5, DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss VV"));
System.out.println(zonedDateTime5);
String str6 = "04-18-2020 20:50:30";
LocalDateTime localDateTime1 = LocalDateTime.parse(str6, DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss"));
System.out.println(localDateTime1);
}
}
Output:
2020-04-18T20:50:30+05:30
2020-04-18T20:50:30+05:30
2020-04-18T20:50:30-04:00
2020-04-18T20:50:30-04:30
2020-04-18T20:50:30-04:00[America/Montreal]
2020-04-18T20:50:30