Search code examples
javatimetimezoneutclocaltime

Java millis time with hourly resolution


How do I get java time millis in UTC ignoring the minutes and seconds.

For instance : If it is October 10 2019, 1:10:59 AM , it should get the Time or millis for October 10 2019, 1 AM.


Solution

  • Summary:

    Instant
    .now()
    .truncatedTo( 
        ChronoUnit.HOURS 
    )
    .toEpochMilli()
    

    1570600800000


    java.time, the modern Java date and time API has got exactly the method you need: many of the classes have a truncatedTo method for needs like yours.

        Instant now = Instant.now();
        System.out.println("Rough milliseconds:                        " + now.toEpochMilli());
        Instant currentWholeHour = now.truncatedTo(ChronoUnit.HOURS);
        System.out.println("Milliseconds ignoring minutes and seconds: "
                + currentWholeHour.toEpochMilli());
    

    When running this snippet just now the output was:

    Rough milliseconds:                        1570604053787
    Milliseconds ignoring minutes and seconds: 1570600800000
    

    I know very well that the first line is what you asked not to have. I only included it for you to see the difference.

    The truncation happens in UTC. If you are in a time zone whose offset is not a whole number of hours from UTC, the results may not be as you had expected. Examples of such time zones include Asia/Kathmandu, America/St_Johns some of the year also Australia/Lord_Howe.

    Link: Oracle tutorial: Date Time