Saturday 20 August 2022

Java: Get time in milliseconds from Date, Calendar and ZonedDateTime

Get time in milliseconds from Date

Date#getTime() method return the time in milliseconds.

Date date = new Date();
long timeMillis1 = date.getTime();

 

Get time in milliseconds from Calendar

Calendar#getTimeInMillis() method return the time in milliseconds.
Calendar calendar = Calendar.getInstance();
long timeMillis2 = calendar.getTimeInMillis();

Get time in milliseconds from ZonedDateTime

ZonedDateTime zonedDateTime = ZonedDateTime.now();
Instant instant = zonedDateTime.toInstant();
long timeMillis3 = instant.toEpochMilli();

Find the below working application.

 


TimeInMilliseconds.java

package com.sample.app;

import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

public class TimeInMilliseconds {

    public static void main(String[] args) {
        Date date = new Date();
        long timeMillis1 = date.getTime();

        Calendar calendar = Calendar.getInstance();
        long timeMillis2 = calendar.getTimeInMillis();

        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        Instant instant = zonedDateTime.toInstant();
        long timeMillis3 = instant.toEpochMilli();

        System.out.println("timeMillis1 : " + timeMillis1);
        System.out.println("timeMillis2 : " + timeMillis2);
        System.out.println("timeMillis3 : " + timeMillis3);
    }

}

Output

timeMillis1 : 1661059945266
timeMillis2 : 1661059945284
timeMillis3 : 1661059945323





 

 

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment