I am trying to convert time zones with given time in my properties file.
package test1;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class TimeZoneConversion {
private static final String DATE_FORMAT = "yyyy-MM-dd-hh-mm-ss";
public static void main(String[] args) {
String ds = "2019-03-18 13-14-48";
LocalDateTime ldt = LocalDateTime.parse(ds, DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println("ldt : "+ldt);
ZoneId singaporeZoneId = ZoneId.of("Asia/Singapore");
System.out.println("TimeZone : " + singaporeZoneId);
//LocalDateTime + ZoneId = ZonedDateTime
ZonedDateTime asiaZonedDateTime = ldt.atZone(singaporeZoneId);
System.out.println("Date (Singapore) : " + asiaZonedDateTime);
ZoneId newYokZoneId = ZoneId.of("America/New_York");
System.out.println("TimeZone : " + newYokZoneId);
ZonedDateTime nyDateTime = asiaZonedDateTime.withZoneSameInstant(newYokZoneId);
System.out.println("Date (New York) : " + nyDateTime);
DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT);
System.out.println("\n---DateTimeFormatter---");
System.out.println("Date (Singapore) : " + format.format(asiaZonedDateTime));
System.out.println("Date (New York) : " + format.format(nyDateTime));
}
}
SO I am getting error :
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-03-18 13-14-48' could not be parsed: Invalid value for ClockHourOfAmPm (valid values 1 - 12): 13
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at test1.FirstClass.main(FirstClass.java:20)
I do not have AM/PM value in the date time that I getting from properties file. This value is stored in String ds. in the above code I have hardcoded it. How does it work? How to make it work with the time date format which I have given?
You should change the DATE_FORMAT
to:
private static final String DATE_FORMAT = "yyyy-MM-dd HH-mm-ss";
If you refer the DateTimeFormatter docs you see the description as follows:
H hour-of-day (0-23)
In your case you are supplying the hour as the hour-of-day
(HH
) instead of in clock-hour-of-am-pm
(hh a
) format from your properties file. And as 13
( > 12) is not an acceptable value for clock-hour-of-am-pm
without the AM/PM you are getting an exception.
If you want it in clock-hour-of-am-pm
you need to change the format to:
private static final String DATE_FORMAT = "yyyy-MM-dd hh-mm-ss a";
And also add the AM/PM information in the date string:
String ds = "2019-03-18 12-14-48 AM";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With