Reputation: 2605
I have a requirement to convert long epoch time for a multiple Zone (variable) to long epoch time in UTC.
I have been trying to do something like following in joda-time:
long getUTCLong(long timestamp, String timeZone) {
DateTimeZone zone = DateTimeZone.forID(timeZone);
DateTime dt = new DateTime(timestamp, zone);
dt.getMillis();
}
But this does not work. How to do this with new java.time features
Upvotes: 2
Views: 145
Reputation: 159114
Although the question code uses Joda-Time, it is actually asking for solution using Java Time API, so here it is:
static long getUTCLong(long timestamp, String timeZone) {
return Instant.ofEpochMilli(timestamp) // process timestamp as milliseconds since 1970-01-01
.atZone(ZoneOffset.UTC).toLocalDateTime() // get pure date/time without timezone
.atZone(ZoneId.of(timeZone)) // mark the date/time as being in given timezone
.toInstant() // convert to UTC
.toEpochMilli(); // get the epoch time in milliseconds since 1970-01-01
}
Upvotes: 5