import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import scala.util.Try
object Test extends App {
val sourceFormat = DateTimeFormat.forPattern("yyyy/MM/dd")
val targetFormat = DateTimeFormat.forPattern("yyyy-MM-dd")
def parse(str: String): Option[DateTime] = {
Try(DateTime.parse(str, sourceFormat)).toOption
}
val input = "2015/07/11"
val maybeDate = parse(input)
println(maybeDate.map(_.toString(targetFormat)))
// Some("2015-07-11")
}
It's also more efficient to use the parse
method together with a DateTimeFormat
that was pre-computed, otherwise the format will be validated every single time. If you call toString
, internally that will also attempt to rebuild a DateTimeFormat
from a String
once more, which is inefficient.
Unlike the other answer, I would suggest that you never use DateTime.parse("2016/07/26")
, e.g. don't pass a String
argument as there's no internal format cache.
Further more Option.map
doesn't catch errors that can be thrown by DateTime.parse
, so if you only use Option
it will blow up at runtime with an error if the string doesn't parse, instead of properly returning a None
. Using a Try
solves that problem.