Skip to content

Instantly share code, notes, and snippets.

@dtanner
Last active April 12, 2016 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dtanner/3ec8c07cebf68c5af07346fb711d9c99 to your computer and use it in GitHub Desktop.
Save dtanner/3ec8c07cebf68c5af07346fb711d9c99 to your computer and use it in GitHub Desktop.
LocalAndZonedDates
import java.time.LocalDate
import java.time.ZonedDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters
// If you have a date without time information, use a LocalDate. e.g. someone's birthday
LocalDate localDate = new LocalDate(2016, 4, 12)
println localDate.toString() // 2016-04-12
//
// If you need to include time in the date, use ZonedDateTime
//
ZonedDateTime zdt = ZonedDateTime.now()
// when formatting a ZonedDateTime for API communication, you'll typically want to use format(DateTimeFormatter.ISO_INSTANT)
println zdt.format(DateTimeFormatter.ISO_INSTANT) // 2016-04-12T19:20:45.539Z
// examples of other formatters included out of the box in the DateTimeFormatter
println zdt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) // 2016-04-12T14:20:45.539
println zdt.format(DateTimeFormatter.RFC_1123_DATE_TIME) // Tue, 12 Apr 2016 14:20:45 -0500
println zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME) // 2016-04-12T14:20:45.539-05:00[America/Chicago]
// you can also create a custom formatter
DateTimeFormatter hammerTimeFormatter = DateTimeFormatter.ofPattern("MMM dd yyyy GG")
println zdt.format(hammerTimeFormatter) // Apr 12 2016 AD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment