Converting Epoch Time into Minutes: A Guide

Although MadProgrammer is right in saying that date and time calculations can be complex and that it’s better to rely on the date and time API, I think this is an exception where simple math can yield accurate results. There are three possible solutions to consider: Solution 1, Solution 2, and Solution 3. If you have Python installed, you can try the second solution. Alternatively, you can use the online version of Unix Epoch, Epoch Converter.

Solution 1:

Utilizing only mathematics to accomplish the task, particularly considering the inclusion of leap years, would be an arduous undertaking. It is advisable to employ established APIs, as they will handle the difficult aspects of the task.

Employ the subsequent approach to accomplish this task.

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(1513213212* 1000L);
System.out.println(cal.get(Calendar.HOUR));//12 hour clock
System.out.println(cal.get(Calendar.HOUR_OF_DAY));//24 hour clock

Solution 2:

Employ the JSR-310, which is alternatively referred to as
modern java date and time api
by utilizing



    LocalTime timeOfDay = Instant.ofEpochSecond(1513213212L)
    int hourOfDay = timeOfDay.getHour();

This prints:


I would opt for utilizing standard library methods to perform mathematical operations, even if your intention is solely to carry out calculations.

    long epochSeconds = 1513213212L;
    // convert the seconds to days and back to seconds to get the seconds in a whole number of days
    long secondsInWholeDays = TimeUnit.DAYS.toSeconds(TimeUnit.SECONDS.toDays(epochSeconds));
    long hourOfDay = TimeUnit.SECONDS.toHours(epochSeconds - secondsInWholeDays);

The code


is also printed.

You expressed the desire to retrieve the current hour in UTC from a given epoch time (e.g. 1513213212) and indicated a preference for a code snippet that best achieves this goal. Please specify which code snippet you would choose.

Although MadProgrammer’s comment about the complexity of date and time arithmetic being a valid concern and deferring to the date and time API is correct, I think that in this particular instance, simple math can provide the correct answer. However, it is important to note that this approach relies on the assumption that leap seconds are not a concern, and you should verify this before using the math solution. Despite this, I would still not recommend using it.

Frequently Asked Questions