Zonedatetime
I have a DTO which returns year, month, day and hour. So passing the value from the DTO to ZonedDateTime.of method. Here, the time is being passed as 10AM PST. So, trying to convert that to UTC.
When passing month as 5, it returns the start time 17PM and when passing month as 2 it is returning the start time as 18PM UTC. It is considering day light saving. It is supposed to be 18PM UTC always irrespective of the month. Is there any way to ignore day light saving here?
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
final ZonedDateTime jobStartDateTimeZ = ZonedDateTime.of(2017, 5, 1, 10,
0, 0, 0, tz.toZoneId());
Instant startTime = jobStartDateTimeZ.withZoneSameInstant(ZoneOffset.UTC).toInstant();
System.out.println("Start Time "+startTime);
We use a legacy system and the string will be in "America/Los_Angeles" in DB and there can be any time zone like "America/Bahia". We want to handle with this format for any timezone.
It may be a hack; but it works.
ZoneId tz = ZoneId.of("America/Los_Angeles");
final ZonedDateTime jobStartDateTimeZ = ZonedDateTime.of(2017, 5, 1, 10, 0, 0, 0, tz);
Instant startTime = jobStartDateTimeZ.toInstant();
// add summer time (DST)
startTime = startTime.plus(tz.getRules().getDaylightSavings(startTime));
System.out.println("Start Time " + startTime);
This prints
Start Time 2017-02-01T18:00:00Z
This doesn't depend on the time zone being America/Los_Angeles or Pacific/Pitcairn, it doesn't depend on the time zone using summer time (DST) or not. It just compensates for the summer time if one is in effect at the instant in question. If no summer time, 0 is added.
As an aside, don't use the outdated TimeZone
class. The modern ZoneId
is a fine replacement. Also withZoneSameInstant()
is unnecessary when you convert to Instant
afterwards anyway,
上一篇: PHP转换HTML格式化日期
下一篇: Zonedatetime