ps0604
ps0604

Reputation: 1071

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");
df.setLenient(false);

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.

Upvotes: 5

Views: 15769

Answers (1)

radumanolescu
radumanolescu

Reputation: 4161

java.time

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

2014

val monthNumber = d.getMonthValue

11

You can access a Month enum object.

val month = d.getMonth

Month.NOVEMBER

val dayOfMonth = d.getDayOfMonth

13

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)

Upvotes: 11

Related Questions