Create a Date from a Unix Timestamp in Java

06 May 2023 Balmiki Mandal 0 Core Java

Create Date From Unix Timestamp in Java

A Unix timestamp is a number of seconds since January 1st, 1970. It can be used to keep track of when a certain event or action took place. In Java, you can use the java.util.Date and java.util.Calendar classes to convert a Unix timestamp into a date and time.

Convert Unix Timestamp to Date

The following example shows how to create a Date object from a Unix timestamp:

long unixSeconds = 1583246800;
// convert seconds to milliseconds
Date date = new Date(unixSeconds*1000L); 
// format of the date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // 03/12/2020 10:00:00 EDT

Convert Unix Timestamp to Calendar

The following example shows how to create a Calendar object from a Unix timestamp:

long unixSeconds = 1583246800;
// convert seconds to milliseconds
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(unixSeconds*1000L); 
// format of the date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(calendar.getTime());
System.out.println(formattedDate); // 03/12/2020 10:00:00 EDT

The code above creates a Date object and a Calendar object from a Unix timestamp. The output is the same in both cases, so you can use either one depending on your needs.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.