1

I am trying to split a number, like

20130405

into three parts: year, month and date.One way is to convert it to string and use regex. Something like:

(\d{4})(\d{2})(\d{2}).r

A better way is to divide it by 100. Something like:

var date = dateNumber
val day = date % 100
date /= 100
val month = date % 100
date /= 100
val year = date

I get itchy while using 'var' in Scala. Is there a better way to do it?

Core_Dumped
  • 4,577
  • 11
  • 47
  • 71

4 Answers4

3

I would go with the former:

scala> val regex = """(\d{4})(\d{2})(\d{2})""".r
regex: scala.util.matching.Regex = (\d{4})(\d{2})(\d{2})

scala> val regex(year, month, day) = "20130405"
year: String = 2013
month: String = 04
day: String = 05
Shadowlands
  • 14,994
  • 4
  • 45
  • 43
  • Isn't regex a rather heavy operation? Dividing would be better, I guess. – Core_Dumped Oct 25 '13 at 13:28
  • 1
    Unless you are parsing an epic number of dates and find that this is your bottleneck for performance, I'd say it is premature optimisation to worry too much about that at this stage. The code I give feels clean and straight-forward (to me), and the regex could be defined elsewhere if it helps separation of concerns, etc. Go for what is better code structure over outright performance until you _know_ where your critical code is going to be. – Shadowlands Oct 25 '13 at 13:33
1

This is probably not much better than your own solution, but it doesn't use var and doesn't require transforming the number to a string. On the other hand, it's not very safe - if you're not 100% sure that your number is going to be well formatted, better use a SimpleDateFormat - granted, it's more expensive, but at least you're safe from illegal input.

val num = 20130405
val (date, month, year) = (num % 100, num / 100 % 100, num / 10000)

println(date)  // Prints 5
println(month) // Prints 4
println(year)  // Prints 2013

I'd personally use a SimpleDateFormat even if I were sure the input will always be legal. The only certainty there is is that I'm wrong and the input will someday be illegal.

Nicolas Rinaudo
  • 6,068
  • 28
  • 41
0

Better than substring would be to use the java Date and SimpleDateFormat classes, see:

https://stackoverflow.com/a/4216767/88588

Community
  • 1
  • 1
Samuel Parkinson
  • 2,992
  • 1
  • 27
  • 38
0

Not very scala-ish but...

scala> import java.util.Calendar
import java.util.Calendar

scala> val format = new java.text.SimpleDateFormat("yyyyMMdd")
format: java.text.SimpleDateFormat = java.text.SimpleDateFormat@ef87e460

scala> format.format(new java.util.Date())
res0: String = 20131025

scala> val d=format.parse("20130405")
d: java.util.Date = Fri Apr 05 00:00:00 CEST 2013

scala> val calendar = Calendar.getInstance
calendar: java.util.Calendar = [cut...]

scala> calendar.setTime(d)

scala> calendar.get(Calendar.YEAR)
res1: Int = 2013
Paolo Falabella
  • 24,914
  • 3
  • 72
  • 86