-1

I have this date in this format:

String date = "2018-12-08T07:50:00+01:00";

And I'd like to get the local time in this format (adding the hours over GMT) but I'm not able to do it

date = "2018-12-08 08:50:00";

Other example:

String date = "2018-12-08T07:50:00+04:00";

Result:

date = "2018-12-08 11:50:00";

Any help?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
hector s.
  • 126
  • 2
  • 9
  • 1
    Similar to [Convert OffsetDateTime to UTC Timestamp](https://stackoverflow.com/questions/30651210/convert-offsetdatetime-to-utc-timestamp) (though likely not a strict duplicate). I think you should be able to piece the answer together from what your search engine can bring you, though. – Ole V.V. Aug 19 '18 at 10:31

2 Answers2

1

As Sun already said in another answer, you misunderstood: 2018-12-08T07:50:00+01:00 is the same point in time as 2018-12-08 06:50:00 in UTC (roughly the same as GMT), not 08:50. +01:00 means that the time comes from a place where the clocks are 1 hour ahead of UTC, so to get the UTC time 1 hour should be subtracted, not added.

    DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String date = "2018-12-08T07:50:00+01:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(date);
    OffsetDateTime dateTimeInUtc = dateTime.withOffsetSameInstant(ZoneOffset.UTC);
    date = dateTimeInUtc.format(desiredFormatter);
    System.out.println(date);

Output from this snippet is:

2018-12-08 06:50:00

Using your other example, 2018-12-08T07:50:00+04:00, the output is

2018-12-08 03:50:00

I am taking advantage of the fact that your string is in ISO 8601 format. OffsetDateTime parses this format as its default, that is, we don’t need to specify the format in a DateTimeFormatter (as we do for your desired result format).

Link: Wikipedia article: ISO 8601

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

2018-12-08T07:50:00+01:00, the +01:00 in the end does not mean adding hh:mm, it means the datetime is already local date time, in GMT it is 2018-12-08T06:50:00.

You can use string.replaceAll to remove T and +01:00:

String input = "2018-12-08T07:50:00+01:00";
input = input.replaceAll("T", " ");
input = input.replaceAll("\\+.*", "");
System.out.println(input);  // 2018-12-08 07:50:00

or parse and re-format it:

OffsetDateTime offsetDateTime = OffsetDateTime.parse("2018-12-08T07:50:00+01:00");
String time = offsetDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).replace("T", " ");
System.out.println(time); // 2018-12-08 07:50:00
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • 1
    I clearly prefer parsing and reformatting over the low-level string operation using regular expressions. Also one should want to store the date-time in a variable of type `OffsetDateTime` anyway. – Ole V.V. Aug 19 '18 at 10:46
  • @OleV.V. If the result is just for UI, then these two approaches does not make difference. Otherwise the second one is preffered. – xingbin Aug 19 '18 at 12:48