Strange Java Timezone Date Conversion Problem

前端 未结 3 778
北荒
北荒 2020-12-04 01:28

I want to convert ms-since-1970-timestamp to a date with timezone (Germany).

Here are two variants of code which worked - at least, I remember using it

3条回答
  •  温柔的废话
    2020-12-04 02:21

    The Answer by Jon Skeet is correct, you used an incorrect time zone name.

    java.time

    Here is a solution using the modern java.time classes that supplant the old legacy date-time classes that have proven to be so troublesome and confusing.

    Instant instant = Instant.ofEpochMilli( milliseconds_since_1970 );  // Or Instant.now() for current moment.
    ZoneId z = ZoneId.of( "Europe/Berlin" ); 
    ZonedDateTime zdt = instant.atZone( z );
    

    Generate a localized string to represent that date-time value.

    Locale l = Locale.GERMANY; // Or Locale.CANADA_FRENCH, etc.
    DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT ).withLocale( l );
    String output = zdt.format( f );
    

提交回复
热议问题