StackTips

How to convert UNIX date to String

madhumita avtar

Written by

Madhumita,  3 min read,  2.61K views, updated on Sept. 17, 2023

In this post we will see how to convert unix date to human readable format, how to use SimpleDateFormat class for date conversion.

  • System.currentTimeMillis()  will give date/time as a single numeric value, expressed as the number of milliseconds after the UNIX epoch. Unix epoch is always an long value. You can convert this time to get your time as per your local time zone.
  • You can use util.Date class object to get the date. Using this you can extract the year, month and day value numerically.
  • Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. You can overload the time zone and locale to get specific time zone time.
  • SimpleDateFormat class is used for parsing and formatting date as text string. We just have to specify the pattern for parsing.

How to get current date

DateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
//getting current date using util.Date class
Date date = new Date();
System.out.println("Current Date:" + dateFormat.format(date));

//or use calendar instance
//Calendar cal = Calendar.getInstance();
//return dateFormat.format(cal.getTime());

Convert UNIX date to String

long unixdate = 1389705117;
DateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(unixdate * 1000);
System.out.println("Formatted Date:" + formatter.format(calendar.getTime()));

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
madhumita avtar

Madhumita

Java and Android developer

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!