ImNeos
ImNeos

Reputation: 567

Date : setTimeZone not detected

I am trying to convert a date in millis 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 see the date, it gives a date which is 2h hours too early. It only gives this issues on the emulator (It is probably not programmed in the local hours). I would like to fix this issues to be sure that I always get the hours in the TimeZone GTM+02 but I don't know how to specificly say that.

I have tried something like 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 the lines : format.setTimeZone(TimeZone.getTimeZone("GTM+02")); seems to be ignored and it still gives the wrong time

Can somebody help? Thanks

Upvotes: 3

Views: 201

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40068

SimpleDateFormat is a legecy one use the 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, for far the most purposes better than specifying an offset is specifying a time zone in region/city format, for example Europe/Brussels:

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

On Android API levels under 26 you need the ThreeTenABP for this, the modern solution to work. See this question: How to use ThreeTenABP in Android Project for a thorough explanation.

Upvotes: 3

xingbin
xingbin

Reputation: 28279

GTM+02 is not a valid ZoneId, I believe it should be GMT+02.

Upvotes: 0

Related Questions