buttowski buttowski - 2 months ago 9
Java Question

How to get date in EST

Please suggest a way to print a date in EST.

public Date convertToEST(Date date)
{
// some code here
}


If I pass in a date in IST, the method should return that date in EST.

Answer

Changing time zones in java

public class TimeZoneSample {
    public static void main(String[] args) throws ParseException {

        // I am in IST time Zone (Its ID is Asia/Calcutta or ITS)
        System.out.println(TimeZone.getDefault());
        // I get Indian Time printed
        System.out.println(new Date());
        System.out.println("-------------------");
        // I am setting the time zone to China
        TimeZone.setDefault(TimeZone.getTimeZone("CTT"));
        // Now my default time zone is in China
        System.out.println(TimeZone.getDefault());
        // I get Chian Time printed
        System.out.println(new Date());
        System.out.println("-------------------");
        // I am setting the time zone to EST
        TimeZone.setDefault(TimeZone.getTimeZone("EST"));
        // Now my default time zone is in EST
        System.out.println(TimeZone.getDefault());
        // I get Eastern Time printed
        System.out.println(new Date());

    }

}

console output

sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
Wed Dec 26 10:22:25 IST 2012
-------------------
sun.util.calendar.ZoneInfo[id="CTT",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null]
Wed Dec 26 12:52:25 CST 2012
-------------------
sun.util.calendar.ZoneInfo[id="EST",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Tue Dec 25 23:52:25 EST 2012