ps0604 ps0604 - 2 months ago 13
Scala Question

Get year, month and day from parsed date

I have the following code to validate a date given a date format:

val df = new SimpleDateFormat("MM/dd/yyyy");

try {
val date = df.parse("11/13/2014");
catch {
case pe: ParseException => println("date error")

Now, what I need is to obtain the year, month and day in three variables. What is the best way to achieve this? Note that I need a solution based on performance as I need to validate/convert thousands of dates.



Use Java 8 and the new date/time API. Better, cleaner, future-proof.

val dateFormat = "MM/dd/yyyy"
val dtf = java.time.format.DateTimeFormatter.ofPattern(dateFormat)
val dateString = "11/13/2014"
val d = java.time.LocalDate.parse(dateString, dtf)
val year = d.getYear


val monthNumber = d.getMonthValue


You can access a Month enum object.

val month = d.getMonth


val dayOfMonth = d.getDayOfMonth


Once you have the input parsed into a java.time.LocalDate, you can get the year with getYear, etc.

To validate, catch the DateTimeParseException generated for invalid inputs.

If you want to skip the proper date validation (e.g. for performance) and just extract the Y, M, D - you can split the string and get integers as shown below

val ymd = dateString.split("/").map(_.toInt)
ymd: Array[Int] = Array(11, 13, 2014)