Syntax error How to get Time in Milliseconds for the Given date and time in Java?

How to get Time in Milliseconds for the Given date and time 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 parse/convert a string as a Date object Instantiate this class by passing desired format string.
  • Parse the date string using the parse() method.
  • You can get the epoch time using the getTime() method.

Example

Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
   public static void main(String args[]) throws ParseException {  
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");      
      //Parsing the given String to Date object
      String str = "25-08-2009 11:20:45";
      Date date = dateformatter.parse(str);  
      long msec = date.getTime();
      System.out.println("Epoch of the given date: "+msec);
   }
}

Output

Epoch of the given date: 1251179445000

You can set date and time values to a calendar object using the set() method. The getTimeInMillis() of this class returns the epoch time of the date value.

Example

Live Demo

import java.util.Calendar;
public class Sample {
   public static void main(String args[]) {  
      Calendar cal = Calendar.getInstance();
      cal.set(2014, 9, 11, 10, 25, 30);
      long msec = cal.getTimeInMillis();
      System.out.print(msec);      
   }
}

Output

1413003330758

You can set date and time values to a ZonedDateTime object using the of() method. The toEpochMilli() of the Instant class returns the epoch time of the date value.

Example

Live Demo

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Sample {
   public static void main(String args[]){  
      //Creating the ZonedDateTime object
      ZoneId id = ZoneId.of("Asia/Kolkata");
      ZonedDateTime obj = ZonedDateTime.of(2014, 9, 11, 10, 25, 30, 22, id);
      Instant instant = obj.toInstant();      
      long msec = instant.toEpochMilli();
      System.out.println("Milli Seconds: "+msec);
   }
}

Output

Milli Seconds: 1410411330000

Updated on: 2021-02-06T04:31:49+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements