Convert epoch milliseconds value to ZonedDateTime

If you have epoch value and wanted to convert epoch milliseconds to ZonedDateTime then you can use ZonedDateTime.ofInstant() and Instant.ofEpochMilli() methods for the conversion.

epoch milliseconds to ZonedDateTime

package com.sneppets.solution;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class EpochMilliToZonedDateTimeExample {
	
	public static void main (String[] args) {
		
		String epochValue = "1573543685000";	
		//330 minutes/ 5:30 hours (client/UI is on GMT IST timezone)
		System.out.println("ZoneId : " + epochMilliSToZDT(epochValue));		
		System.out.println("ZoneOffset : " + epochMilliSToZDT(epochValue, 330));		
		
	}
	
	// Case i) ZoneId 
	private static ZonedDateTime epochMilliSToZDT(String  epochMilliSeconds) {
		Long lEpochMilliSeconds = Long.parseLong(epochMilliSeconds);			
		return ZonedDateTime.ofInstant(
				Instant.ofEpochMilli(lEpochMilliSeconds), ZoneId.systemDefault());
	}
	
	
	//Case ii) ZoneOffset - Adjusting timezone between client and server
	private static ZonedDateTime epochMilliSToZDT(String  epochMilliSeconds, int utcOffsetVal) {
		Long lEpochMilliSeconds = Long.parseLong(epochMilliSeconds);	
		ZoneOffset zoneOffSet= ZoneOffset.ofTotalSeconds(utcOffsetVal * 60);
		return ZonedDateTime.ofInstant(
				Instant.ofEpochMilli(lEpochMilliSeconds), zoneOffSet);
	}	


}

Output

ZoneId : 2019-11-12T12:58:05+05:30[Asia/Calcutta]  //ZonedDateTime
ZoneOffset : 2019-11-12T12:58:05+05:30

ZonedDateTime is a date time with time zone in the below format

2019-11-14T10:15:30+01:00 Europe/Paris.

The above example shows you that you might face similar requirements where in case i) we are using ZoneId.systemDefault() to get the system default time zone and perform conversion i.e., we assume that both UI/client and server are in the same timezone. This is the common case that you may come across.

private static ZonedDateTime epochMilliSToZDT(String  epochMilliSeconds) {
  Long lEpochMilliSeconds = Long.parseLong(epochMilliSeconds);			
  return ZonedDateTime.ofInstant(
		Instant.ofEpochMilli(lEpochMilliSeconds), ZoneId.systemDefault());
}

Case ii) Another challenge that you may face is the epoch milliseconds value from UI is based on different time zone (say for example GMT IST time zone) and backend server/system is based on system timezone which is in different timezone (Europe/Lisbon timezone) then you need to use ZoneOffset for adjustment.

private static ZonedDateTime epochMilliSToZDT(String  epochMilliSeconds, int utcOffsetVal) {
  Long lEpochMilliSeconds = Long.parseLong(epochMilliSeconds);	
  ZoneOffset zoneOffSet= ZoneOffset.ofTotalSeconds(utcOffsetVal * 60);
  return ZonedDateTime.ofInstant(
		Instant.ofEpochMilli(lEpochMilliSeconds), zoneOffSet);
}

Further Learning

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments