Converting date from UTC to EST in Java?

后端 未结 4 1940
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 06:14

I\'m trying to convert a long timestamp that is UTC to Eastern Standard Time and am totally lost. Any hints would be great!

Time format should be : 11/4/03 8:14 PM

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 07:01

    You should not think in terms of converting a Date to a different timezone. Dates in Java are, and should always be, in UTC.

    Rather, you can set a particular timezone when you want to format a Date. Here is an example:

    public static void main(String[] args) throws Exception {
    
        String tzid = "EST";
        TimeZone tz = TimeZone.getTimeZone(tzid);
    
        long utc = System.currentTimeMillis();  // supply your timestamp here
        Date d = new Date(utc);
    
        // timezone symbol (z) included in the format pattern for debug
        DateFormat format = new SimpleDateFormat("yy/M/dd hh:mm a z");
    
        // format date in default timezone
        System.err.println(format.format(d));
    
        // format date in target timezone
        format.setTimeZone(tz);
        System.err.println(format.format(d));
    
    }
    

    Output for me (my default timezone is GMT):

    11/12/19 10:06 AM GMT
    11/12/19 05:06 AM EST
    

    Alternatively, you can set the timezone on a Calendar, and then access the Calendar fields you require. For example:

        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("EST"));
        c.setTimeInMillis(utc);
        System.err.printf("%d/%d/%d %d:%d %s\n", c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR), c.get(Calendar.MINUTE), (c.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM"));
    

    (This does not give you the exact pattern you requested.)

提交回复
热议问题