• Post Reply Bookmark Topic Watch Topic
  • New Topic

java.time.Instant not local time.  RSS feed

 
Markus Schmider
Ranch Hand
Posts: 148
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am just beginnig to learn the new Time API.
When I run

I get the correct date and time.


returns a time two hours earlier. I live in Germany.

From the api doc:
now()
Obtains the current instant from the system clock.

In the book I read nothing is mentioned about using a TimeZone or ZoneId with Instant.
What do I miss?

 
Dave Tolls
Rancher
Posts: 2914
36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instant is UTC I think (can't check as I don't have Java 8 here).
If you want the local time then there's a LocalTime class.
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The API for Instant.toString() says this:
A string representation of this instant using ISO-8601 representation.

The format used is the same as DateTimeFormatter.ISO_INSTANT.

The latter in turn says this:
The ISO instant formatter that formats or parses an instant in UTC, such as '2011-12-03T10:15:30Z'.

You probably missed that Z which is the same as +00:00, UTC and GMT.

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want something that is in your local timezone by default, then use ZonedDateTime instead of Instant:

 
Campbell Ritchie
Marshal
Posts: 55753
163
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I presume you have read the Java™ Tutorials section about dates and times, and the Instant documentation. You find an Instant object represents seconds since 1st January 1970, but in GMT/UTC, along with a nanoseconds field, but one cannot be absolutely certain about its precision compared to an atomic clock somewhere. Least of all when it is taken from a computer's internal clock.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!