3

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

xingbin
  • 25,716
  • 8
  • 51
  • 94
ImNeos
  • 477
  • 5
  • 16
  • The above code is working for me with this change `TimeZone.getTimeZone("GMT+02")` and also you don't need this `toString()` – Deadpool Jul 26 '19 at 16:36
  • It’s one of the confusing traits of the poorly designed and long outdated `TimeZone` class: `TimeZone.getTimeZone("GTM+02")` gives you GMT. Hard to believe, so try it out yourself. – Ole V.V. Jul 26 '19 at 18:36

2 Answers2

3

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.

Ole V.V.
  • 76,217
  • 14
  • 120
  • 142
Deadpool
  • 33,221
  • 11
  • 51
  • 91
0

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

xingbin
  • 25,716
  • 8
  • 51
  • 94