tags:

views:

73

answers:

1

I have a String, representing time in UTC. I need to convert it to long representing milliseconds since midnight at EST, considering daylight saving times. For example, in January, the offset is 5 hours, but in June 4 hours.

However, the code below displays the same offset of 5 hours for both June and January. The variable tzOffset = -18000000 (=-5 hours), regardless the date month.

Please advise,

Thanks!

package TimeConversion;

import java.text.SimpleDateFormat;

import java.util.*;

public class TimeConversion {

    public static void main(String[] args) throws Exception {

        String utcTime = "20100101120000000";
        SimpleDateFormat sdfIn = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        sdfIn.setTimeZone(TimeZone.getTimeZone("UTC"));        
        long utcMillis = sdfIn.parse(utcTime).getTime();
        long tzOffset = TimeZone.getTimeZone("EST").getOffset(utcMillis);
        long estMillis = utcMillis + tzOffset;
        long estMillisSinceMidnight = estMillis % 86400000;
        System.out.println("utcTime = " + utcTime + "\nestMillisSinceMidnight = " + estMillisSinceMidnight + "(" + 24.0 * estMillisSinceMidnight / 86.4e6 + ")");
    }

}
A: 

You could steal some code from this calendar conversion utility. What you probably need is getLocalTime. Disclaimer: I wrote it.

Thomas Mueller