Are you working on Java Enterprise project? What if your customers are located in different Geo location? It’s always good practice to show your users their local time on UI page.
Wondering how to convert time to your user’s local time dynamically? Well, using Java’s getTime()
returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
In this tutorial we will go over simple simple steps on how to convert current time to Epoch time
.
package crunchify.com.tutorial; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Calendar; import java.util.Date; /** * @author Crunchify.com * */ public class CrunchifyEpochTime { public static void main(String[] args) { Date today = Calendar.getInstance().getTime(); // Constructs a SimpleDateFormat using the given pattern SimpleDateFormat crunchifyFormat = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz"); // format() formats a Date into a date/time string. String currentTime = crunchifyFormat.format(today); log("Current Time = " + currentTime); try { // parse() parses text from the beginning of the given string to produce a date. Date date = crunchifyFormat.parse(currentTime); // getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. long epochTime = date.getTime(); log("Current Time in Epoch: " + epochTime); } catch (ParseException e) { e.printStackTrace(); } // Local ZoneID ZoneId defaultZoneId = ZoneId.systemDefault(); log("defaultZoneId: " + defaultZoneId); Date date = new Date(); // Default Zone: UTC+0 Instant instant = date.toInstant(); System.out.println("instant : " + instant); // Local TimeZone LocalDateTime localDateTime = instant.atZone(defaultZoneId).toLocalDateTime(); System.out.println("localDateTime : " + localDateTime); } // Simple logging private static void log(String string) { System.out.println(string); } }
Just run above program as Java Application
in Eclipse IDE and you are all set.
Eclipse console output:
Current Time = Feb 16 2018 23:17:20.398 CST Current Time in Epoch: 1518844640398 defaultZoneId: America/Chicago instant : 2018-02-17T05:17:20.484Z localDateTime : 2018-02-16T23:17:20.484