Last active
April 14, 2016 21:57
-
-
Save P7h/1c3f239ed070e0cfe490354ccb5c4b81 to your computer and use it in GitHub Desktop.
Formatting and parsing date and time with Java 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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