Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Formatting and parsing date and time with Java 8
import java.time._
import java.time.format.DateTimeFormatter
val date = "Sun Apr 03 05:40:58 +0200 2016"
val formatter = DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss ZZ yyyy")
val parsedDate = LocalDateTime.parse(date, formatter)
// parsedDate: java.time.LocalDateTime = 2016-04-03T05:40:58
val parsedDateTZ = ZonedDateTime.parse(date, formatter)
// parsedDateTZ: java.time.ZonedDateTime = 2016-04-03T05:40:58+02:00
// Note: Because TimeZone is present in the format string, we cant use LocalDateTime and should use ZonedDateTime
// val now = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss ZZ yyyy")
val now = ZonedDateTime.now()
val formattedDate1 = formatter.format(now)
// formattedDate1: String = Sun Apr 03 22:50:01 +0100 2016
val formattedDate2 = now.format(formatter)
// formattedDate2: String = Sun Apr 03 22:50:01 +0100 2016
// Format string without TimeZone
val formatter = DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss yyyy")
val now = LocalDateTime.now()
val formattedDate1 = formatter.format(now)
// formattedDate1: String = Sun Apr 03 22:51:07 2016
val formattedDate2 = now.format(formatter)
// formattedDate2: String = Sun Apr 03 22:51:07 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.