简体   繁体   中英

How can I get the hour of the day from milliseconds in Android

I was looking for the answer on the web but no one answers exactly what I want. Say I have a milliseconds from epoch, System.getCurrentMillis() . I need to know the hour of the day of said millis, just the hour, from 00 to 24, ideally not as a string, but as an int.

Is there a easy way to achieve this. Currently I'm using SimpleDateFormat("HH") to get the string with dateFormat , but I'm sure there must be a better practice.

Thanks beforehand

Calendar time = Calendar.getInstance();
time.setTimeInMillis(milliseconds);
time.get(Calendar.HOUR_OF_DAY)

Another working solution for those who don't want to use Calendar constructor. Attention: this works only for Time Zone offset = 0!

//extracts Hour Of Day from Calendar milliseconds (TimeZone = 0)
public static int extractHourOfDayFromMS(long ms) {
    int millis = (int) (ms % 86400000);

    if (millis < 0) {
        millis += 86400000;
    }
    while (millis < 0) {
        millis += 86400000;
    }
    while (millis >= 86400000) {
        millis -= 86400000;
    }
    millis /= (1000*60*60);
    return millis % 24;
}

This code was adapted from GregorianCalendar.fullFieldsCalc() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM