-1

I have got a String of Date which has the nonstandard GMT format, like "2016-08-31T02:04:58.893GMT". Now I need to transfer it to Local time format, like "2016-08-31 10:04:58". By the way, I am in China, there's 8 hours between the Local time and GMT time. Oh, I use Java. Thank everyone.

jlucky
  • 144
  • 2
  • 6

2 Answers2

1

You parse the string using DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz").

Example code, showing intermediate results:

String input = "2016-08-31T02:04:58.893GMT";

DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
ZonedDateTime zdtGMT = ZonedDateTime.parse(input, fmt1);
System.out.println(zdtGMT);           // prints 2016-08-31T02:04:58.893Z[GMT]

ZonedDateTime zdtChina = zdtGMT.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
System.out.println(zdtChina);         // prints 2016-08-31T10:04:58.893+08:00[Asia/Shanghai]

LocalDateTime ldt = zdtChina.toLocalDateTime();
System.out.println(ldt);              // prints 2016-08-31T10:04:58.893

DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(ldt.format(fmt2)); // prints 2016-08-31 10:04:58
Andreas
  • 154,647
  • 11
  • 152
  • 247
-1

You'd better transform the non-standard GMT format to a standard time format and then use some proper built-in function to add or subtract a difference. You may use another function to transform the standard time format to your designated format.

This will be great because you don't have to consider the complicated cases, for example, "2016-12-31 23:00" + 8hrs.

Jason Huh
  • 39
  • 5