Parse and retrieve timezone offset from date-time

后端 未结 4 409
深忆病人
深忆病人 2020-12-22 05:37

Date format: \"yyyy-MM-dd\'T\'HH:mm:ss.SSSZ\"

Input date: \"2017-09-18T03:08:20.888+0200\"

Problem: I need retrieve timezon

4条回答
  •  爱一瞬间的悲伤
    2020-12-22 06:21

    SimpleDateFormat extends DateFormat and thus internally uses a Calendar. When parsing the date that calendar is being updated so you can get the timezone from it after parsing:

    //use the timezone of the internally stored calendar
    outputSdf.setTimeZone( inputSdf.getTimezone() );
    

    That also shows why DateFormat is not threadsafe.

    EDIT:

    It seems the internal calendar's timezone isn't updated but the ZONE_OFFSET field is. Hence you could do something like this:

    int zoneOffset = inputSdf.getCalendar().get( Calendar.ZONE_OFFSET );
    //length check etc. left for you
    String matchingZoneId = TimeZone.getAvailableIDs( zoneOffset )[0];
    outputSdf.setTimeZone( TimeZone.getTimeZone( matchingZoneId ) );
    

    Note that you can't just set the zone offset of the output format since that won't update the timezone reference which is used when formatting.

    As you can see doing it this way looks a little "hacky" and thus you should think hard on whether you really need the timezone. In most cases you'd define the output timezone in a different way anyways, e.g. by getting the user's location, input, etc.

提交回复
热议问题