Syntax error How to get (format) date and time from mill seconds in Java?

How to get (format) date and time from mill seconds in Java?



The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string.

One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object.

To format milli seconds to date −

  • Create the format string as dd MMM yyyy HH:mm:ss:SSS Z.
  • The Date class constructor accepts a long value representing the milliseconds as a parameter and creates a date object.
  • Finally format the date object using the format() method.

Example

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
   public static void main(String args[]) throws ParseException {
      long msec = 3550154;
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat dateformatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
      //Parsing the given String to Date object
      Date date = new Date(msec);
      System.out.println("Date value: "+dateformatter.format(date));
   }
}

Output

Date value: 01 Jan 1970 06:29:10:154 +0530

Example

import java.util.Calendar;
import java.util.Date;
public class Sample {
   public static void main(String args[]) {
      Calendar calendar = Calendar.getInstance();
      long msec = calendar.getTimeInMillis();
      Date obj = new Date(msec);
      System.out.println(obj);
   }
}

Output

Wed Nov 11 22:04:59 IST 2020

Updated on: 2021-09-07T13:12:20+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements