Converting UTC dates to other timezones

后端 未结 5 557
礼貌的吻别
礼貌的吻别 2020-11-29 21:55

I\'m converting a UTC time to another timezone, using this method:

SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");
Date parsed = for         


        
5条回答
  •  盖世英雄少女心
    2020-11-29 22:21

    Following code works fine for me to change a date from one tz to another. It considers the DayLightSaving also.

    public static Calendar changeTimezoneOfDate(Date date, TimeZone fromTZ, TimeZone toTZ) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        long millis = calendar.getTimeInMillis();
        long fromOffset = fromTZ.getOffset(millis);
        long toOffset = toTZ.getOffset(millis);
        long convertedTime = millis - (fromOffset - toOffset);
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(convertedTime);
        return c;
    }
    

提交回复
热议问题