Search code examples
androidcalendartimestamptimestamp-with-timezone

best way to get timestamp in long in android?


I want to understand this in detail on how to get this in android and which method to follow and please explain bit more to understand in better way ?

As we have some options to get this in android and find out the best.

It will be helpful if somebody explains with code how to get this.

Thanks in advance for your help


Solution

  • Hi I hope this will help you

    //Getting the current date
          Date date = new Date();
          //This method returns the time in millis
          long timeMilli = date.getTime();
          System.out.println("Time in milliseconds using Date class: " + timeMilli);
    
          //creating Calendar instance
          Calendar calendar = Calendar.getInstance();
          //Returns current time in millis
          long timeMilli2 = calendar.getTimeInMillis();
          System.out.println("Time in milliseconds using Calendar: " + timeMilli2);
    
          //Java 8 - toEpochMilli() method of ZonedDateTime
          System.out.println("Getting time in milliseconds in Java 8: " + 
          ZonedDateTime.now().toInstant().toEpochMilli());
    

    And output fo these options will be

    Time in milliseconds using Date class: 1508484583259

    Time in milliseconds using Calendar: 1508484583267

    Getting time in milliseconds in Java 8: 1508484583331

    if we convert those long values to the date format then all three will be the same and it will be

    Input   1508484583259
    Input (formatted)   1,508,484,583,259
    Date (Etc/UTC)  Friday, October 20, 2017 7:29:43 AM UTC
    Date (GMT)  Friday, October 20, 2017 7:29:43 AM GMT
    Date (short/short format)   10/20/17 7:29 AM
    

    Over here I posted only one option result but all three will be the same or you can also check it by your own on online long to date convertor.