How to get current date/time in milli seconds in Java?

JavaServer Side ProgrammingProgramming

The getTime() method of the Date class retrieves and returns the epoch time (number of milliseconds from Jan 1st 1970 00:00:00 GMT0.

Example

Live Demo

import java.util.Date;
public class Sample {
   public static void main(String args[]){  
      //Instantiating the Date class
      Date date = new Date();
      long msec = date.getTime();
      System.out.println("Milli Seconds: "+msec);
   }
}

Output

Milli Seconds: 1605160094688

The getTimeInMillis() method of the calendar class retrieves and returns the time in milli seconds from the epochepoch time (Jan 1st 1970 00:00:00 GMT).

Example

Live Demo

import java.util.Calendar;
public class Sample {
   public static void main(String args[]){  
      //Creating the Calendar object
      Calendar cal = Calendar.getInstance();
      long msec = cal.getTimeInMillis();
      System.out.println("Milli Seconds: "+msec);
   }
}

Output

Milli Seconds: 1605160934357

The toEpochMilli() method of the Instant class  returns the milliseconds from the epoch.

Example

Live Demo

import java.time.Instant;
import java.time.ZonedDateTime;
public class Sample {
   public static void main(String args[]){  
      //Creating the ZonedDateTime object
      ZonedDateTime obj = ZonedDateTime.now();
      Instant instant = obj.toInstant();
      long msec = instant.toEpochMilli();
      System.out.println("Milli Seconds: "+msec);
   }
}

Output

Milli Seconds: 1605162474464

raja
Published on 06-Feb-2021 04:28:45
Advertisements