How to set time zone of a java.util.Date?

后端 未结 10 1940
我寻月下人不归
我寻月下人不归 2020-11-22 01:45

I have parsed a java.util.Date from a String but it is setting the local time zone as the time zone of the date object.

The ti

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 02:12

    If you must work with only standard JDK classes you can use this:

    /**
     * Converts the given date from the fromTimeZone to the
     * toTimeZone.  Since java.util.Date has does not really store time zome
     * information, this actually converts the date to the date that it would be in the
     * other time zone.
     * @param date
     * @param fromTimeZone
     * @param toTimeZone
     * @return
     */
    public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
    {
        long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
        long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);
    
        return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
    }
    
    /**
     * Calculates the offset of the timeZone from UTC, factoring in any
     * additional offset due to the time zone being in daylight savings time as of
     * the given date.
     * @param date
     * @param timeZone
     * @return
     */
    private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
    {
        long timeZoneDSTOffset = 0;
        if(timeZone.inDaylightTime(date))
        {
            timeZoneDSTOffset = timeZone.getDSTSavings();
        }
    
        return timeZone.getRawOffset() + timeZoneDSTOffset;
    }
    

    Credit goes to this post.

提交回复
热议问题