I am having difficulty using JodaTime to handle Daylight savings time.
String time = "3:45-PM";
DateTimeFormatter formatter = DateTimeFormat.forPattern("KK:mm-a");
DateTime dt = formatter.parseDateTime(time).withZone(DateTimeZone.forID("America/New_York"));
dt = dt.toDateTime(DateTimeZone.UTC);
startDate = startDate.withHourOfDay(dt.getHourOfDay()).withMinuteOfHour(dt.getMinuteOfHour());
Output from this code snippet ends up being:
2015-04-08 16:46:51.952 INFO 12244 --- [nio-8080-exec-1] VALUES PULLED : 03:45-PM
2015-04-08 16:46:51.952 INFO 12244 --- [nio-8080-exec-1] VALUES PULLED : 08:45-PM
Currently, the time is 5 hours off. Which is not handling Daylights saving time. How do I get Joda Time to take DLS into account?
This happens because the DateTime
object that you get after parsing is set to the date 01-01-1970
. It looks like you expect that it would be set to today, but it isn't.
If you want the time to be interpreted as 3:45 PM today in the timezone America/New_York
, do this:
String time = "3:45-PM";
DateTimeFormatter formatter = DateTimeFormat.forPattern("KK:mm-a")
.withZone(DateTimeZone.forID("America/New_York"));
DateTime dt = formatter.parseDateTime(time)
.withDate(LocalDate.now());
System.out.println(dt);
System.out.println(dt.withZone(DateTimeZone.UTC));
Note: You need to set the zone on the DateTimeFormatter
.