Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

java 8 - How to convert from Instant to LocalDate

I have an Instant coming from a source that should, according to the spec, be a LocalDate, but don't see any methods in LocalDate for the conversion. What is the best way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Java 9+

LocalDate.ofInstant(...); arrived in Java 9.

Instant instant = Instant.parse( "2020-01-23T00:00:00Z" );
ZoneId z = ZoneId.of( "America/Edmonton" );
LocalDate ld = LocalDate.ofInstant( instant , z );

See code run live at IdeOne.com.

Notice the date is 22nd rather than 23rd as that time zone uses an offset several hours before UTC.

2020-01-22

Java 8

ZonedDateTime has a .toLocalDate() method in Java 8.

yourInstant.atZone(yourZoneId).toLocalDate(); Will work with earlier versions for LocalDate...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...