deltanovember deltanovember - 1 year ago 67
Java Question

How do I convert "fraction of day" to Java time?

I'm working with the Excel format where


Means that we are 65.49% through the day. How would I convert this to a nice looking time such as

15:30:42 PM

in Java?

Answer Source

Try this:

public static void main(String[] args) throws Exception {
    DateFormat format = new SimpleDateFormat("HH:mm:ss a");
    for(String fracStr : args) {
        double frac = Double.parseDouble(fracStr);
        long day = (long) Math.floor(frac);
        frac = frac - day;
        Date time = new Date((long) ( 86400000l * frac));
        System.out.println(fracStr+" -> "+format.format(time));

A little note here - the GMT time zone may not get you the results you expect, but UTC will. This is because Java considers GMT as a valid abbreviation for Europe/London and between 1968 and 1972 London was on permanent daylight saving. So midnight 1st January 1970 GMT (the Java epoch) is also 1am 1st January 1970 (GMT).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download