-3

how to parse yyyy-mm-ddThh:mm:ssZ into my specific timezone and only display the time?

For example: from 2017-11-22T22:00:00Z to 2017-11-22 23:00

Because my timezone is one hour ahead of the timezone that the first string was from, I hope you understand!

Frans
  • 69
  • 2
  • 9
  • See also https://stackoverflow.com/questions/27340650/how-to-convert-a-instant-to-a-localtime – erickson Nov 22 '17 at 20:40
  • Your use of the year `0001` raises calendar issues connected to year zero, and trying to represent historic dates. If your actual Question is about contemporary times, edit to show that. – Basil Bourque Nov 22 '17 at 20:58
  • Search Stack Overflow before posting. Issues of parsing an ISO 8601 string, adjusting into a time zone, and extracting a time-of-day have all been handled many times already. – Basil Bourque Nov 22 '17 at 21:01

3 Answers3

4

If using Java 8, you can parse it as an Instant and then convert it to a ZonedDateTime in the time zone you need. You can then get the local time from the ZonedDateTime.

Instant instant = Instant.parse("2017-11-22T22:00:00Z");
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println(zdt.toLocalTime());

You can also specify a specific Zone ID other than the system default. To see the available Zone IDs to choose from, use ZoneId.getAvailableZoneIds())

Using ZonedDateTime will handle daylight savings. If you simply need a static hour offset, you can convert it to an OffsetDateTime instead of the ZonedDateTime.

Jared Gommels
  • 401
  • 4
  • 13
  • Correct. Alternatively, you can call `Instant::atZone` to produce a `ZonedDateTime`. No better, just a matter of taste. – Basil Bourque Nov 22 '17 at 20:54
  • *FYI:* Funny results for `America/New_York` time zone: `19:03:58`. Caused by time zone for New York prior to 1883 being `UTC -4:56:02`. – Andreas Nov 22 '17 at 21:01
1

First, parse your string as an Instant, then convert that to a ZoneDateTime in the desired zone; from that, you can obtain the LocalTime

LocalTime time = Instant.parse(str).atZone(ZoneId.systemDefault()).toLocalTime();
erickson
  • 249,448
  • 50
  • 371
  • 469
-1

Java DateFormater

String date = "2011-01-18 00:00:00";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); 
Date parsedDate = dateFormat.parse(date);
G.Vitelli
  • 1,022
  • 7
  • 15