Java – Date : setTimeZone not detected

Date : setTimeZone not detected… here is a solution to the problem.

Date : setTimeZone not detected

I’m trying to convert a date in milliseconds to a date and get the time.

I have this code:

 long yourmilliseconds = Long.parseLong(model_command.getTime());
    Date resultdate = new Date(yourmilliseconds);

When I debug and look at the date, it gives the date 2 hours earlier. It only gives this issue on the emulator (it may not be programmed in local time). I’d like to fix this to make sure I always get time in TimeZone GTM+02, but I don’t know how to be specific.

I’ve tried this:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    long yourmilliseconds = System.currentTimeMillis();
    Date resultdate = new Date(yourmilliseconds);
    format.setTimeZone(TimeZone.getTimeZone("GTM+02"));
    String test = format.format(resultdate).toString(); /**DATE**/

But line: format.setTimeZone(TimeZone.getTimeZone("GTM+02"));
Seems to be ignored, it still gives the wrong time

Can someone help? Thanks

Solution

SimpleDateFormat is a traditional method using ZonedDateTime and Instant from Java 8

OffsetDateTime i = Instant.ofEpochMilli(yourmilliseconds)
        .atOffset(ZoneOffset.ofHours(2));

String dateTime = i.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));  2019-07-26 18:01:49

However, in

most cases, a better way than specifying an offset is to specify the time zone in region/city format, such as Europe/Brussels:

ZonedDateTime i = Instant.ofEpochMilli(yourmilliseconds)
        .atZone(ZoneId.of("Europe/Brussels"));

At the Android API level below 26, you need to ThreeTenABP for this, modern solutions work. Look at this question: How to use ThreeTenABP in Android Project for a thorough explanation.

Related Problems and Solutions