Last active
January 19, 2021 09:21
-
-
Save fokot/14cdfead58204b6cb2d217bd61bf733f to your computer and use it in GitHub Desktop.
Scala date parsing with optional time and optional time zone
This file contains 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.format.{ DateTimeFormatterBuilder} | |
import java.time.format.DateTimeFormatter.{ISO_LOCAL_DATE, ISO_LOCAL_TIME} | |
import java.time.{LocalDate, LocalDateTime, OffsetDateTime, ZoneOffset} | |
import scala.util.{Success, Try} | |
object DateParsing extends App { | |
private val formatter = new DateTimeFormatterBuilder() | |
.parseCaseInsensitive | |
.append(ISO_LOCAL_DATE) | |
.optionalStart() | |
.appendLiteral('T') | |
.append(ISO_LOCAL_TIME) | |
.optionalStart | |
.appendOffsetId | |
.toFormatter | |
def dateFromISOEither(s: String): Either[String, OffsetDateTime] = | |
Try(formatter.parseBest(s, OffsetDateTime.from(_), LocalDateTime.from(_), LocalDate.from(_))) match { | |
case Success(a: OffsetDateTime) => Right(a) | |
case Success(a: LocalDateTime) => Right(a.atZone(ZoneOffset.UTC).toOffsetDateTime) | |
case Success(a: LocalDate) => Right(a.atStartOfDay(ZoneOffset.UTC).toOffsetDateTime) | |
case _ => Left(s"Error parsing $s to OffsetDateTime") | |
} | |
List( | |
"2021-01-19", | |
"2021-01-19T10:04:35", | |
"2021-01-19T10:04:35Z", | |
"2021-01-19T10:04:35+01:00", | |
).map(dateFromISOEither).foreach(println) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment