Search code examples
javadatetimeutc

Converting UTC timestamp to local date


So I tried now for about hours to convert a Timestamp to a local date (CEST).

     Date date = new Date(stamp*1000);
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     simpleDateFormat.setTimeZone(TimeZone.getTimeZone("CEST"));
     String myDate = simpleDateFormat.format(date);

It's not working whatever I tried and looked up in Internet I always get back the UTC time......

for better understanding: stamp is a variable timestamp with type long which I will receive from a service


Solution

  • tl;dr

    String output = ZonedDateTime.ofInstant ( Instant.ofEpochSecond ( 1_468_015_200L ) , ZoneId.of ( "Europe/Paris" ) ).toString();
    

    Details

    A few issues:

    • You are not using proper time zone names.
      • Proper names are in continent/region format.
      • The 3-4 letter abbreviations so commonly seen in the media such as CEST are not true time zones. Avoid them. They are neither standardized nor unique(!).
    • You are using old outmoded date-time classes that are poorly designed and confusing. They have been supplanted by the java.time framework.

    If by CEST you meant 2 hours ahead of UTC in the summer, then let's take Europe/Paris as an example time zone. Your Question lacks example data, so I'll make up this example.

    Apparently your input is a count of whole seconds from the epoch of first moment of 1970 in UTC. That value can be used directly, no need to multiply.

    The ZoneId class represents the time zone. An Instant is a point on the timeline in UTC with a resolution up to nanoseconds. A ZonedDateTime is the Instant adjusted into the ZoneId.

    ZoneId zoneId = ZoneId.of ( "Europe/Paris" );
    long input = 1_468_015_200L;   // Whole seconds since start of 1970.
    Instant instant = Instant.ofEpochSecond ( input );
    ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
    

    Dump to console.

    System.out.println ( "input: " + input + " | instant: " + instant + " | zdt: " + zdt );
    

    input: 1468015200 | instant: 2016-07-08T22:00:00Z | zdt: 2016-07-09T00:00+02:00[Europe/Paris]