I'm trying to display the events of a google calendar using the google calendar API in java. But I don't have any idea on how to get the date (and time) of my events in a nice looking format. The only thing I can do is the following:
DateTime now = new DateTime(System.currentTimeMillis());
Events events = service.events().list("primary")
.setMaxResults(7)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
items = events.getItems();
items.get(0).getStart().getDateTime();
which leads to the following output: 2018-11-06T18:00:00.000+01:00
Any idea on how to get it eg as a Date Object?
According to the Google API reference the type DateTime
has a method getValue()
which
Returns the date/time value expressed as the number of milliseconds since the Unix epoch.
To get an java.util.Date
we can use this long
value:
Date date = new Date(items.get(0).getStart().getDateTime().getValue());
But note that since Java 8 there is the java.time API. To get a LocalDateTime
you can go on like that:
ZoneOffset offset = ZoneOffset.ofTotalSeconds(items.get(0).getStart().getDateTime().getTimeZoneShift() * 60);
ZoneId zone = ZoneId.ofOffset("UTC", offset);
Instant instant = date.toInstant();
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, zone);
To determine the appropriate ZoneId
we use the method getTimeZoneShift()
which
Returns the time zone shift from UTC in minutes or 0 for date-only value.
Since ZoneId.ofOffset
takes as second parameter a value in seconds, we have to convert the minutes returned by getTimeZoneShift()
to seconds first.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.