Reputation: 279
I read over the literature for ZonedDate and Instant and found that I can convert a local time to utc via the below:
LocalDate d = LocalDate.now();
LocalTime time = LocalTime.of(00, 00, 00);
ZoneId zone = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = ZonedDateTime.of(d, time, zone);
System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
Instant instant = zonedDateTime.toInstant();
System.out.println(instant);
The problem is the output looks like this:
2018-11-26T00:00:00
2018-11-26T08:00:00Z
I'm trying to get both strings in the format of "yyyy-MM-dd HH:mm:ss" but am having a hard time getting anything to work properly. Since I am using the output to query an MYSQL database I could just manually do:
String zoneDate = zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
String utcDate = zonedDateTime.toInstant().toString();
zoneDate = zoneDate.replace('T', ' ').replace('Z', ' ');
utcDate = utcDate.replace('T', ' ').replace('Z', ' ');
With my new output being:
2018-11-26 00:00:00
2018-11-26 08:00:00
But I feel like this is bad practice and there should be a method to convert to the proper format within the classes. Is there such a way to perform formatting as above from the default classes?
Upvotes: 1
Views: 2186
Reputation: 244
Follow snippet below.
LocalDate d = LocalDate.now();
LocalTime time = LocalTime.now();
ZoneId zone = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = ZonedDateTime.of(d, time, zone);
String zoneDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(zonedDateTime);
ZonedDateTime utcZonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of(ZoneOffset.UTC.getId()));
String utcZoneDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(utcZonedDateTime);
System.out.println(zoneDate);
System.out.println(utcZoneDate);
Output for this is
2018-11-26 02:20:08
2018-11-26 10:20:08
For more information please visit java doc -> https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
Upvotes: 1