I've got date and time in separate fields, in yyyyMMdd and HHmmss formats respectively. To parse them I think to construct a yyyy-MM-ddTHH:mm:ss string and feed this to joda-time constructor. So I am looking to get 1-st 4 digits, then 2 digits starting from the index 5, etc. How to achieve this? List.fromString(String) (which I found here) seems to be broken.
The substring
method certainly can get you there but String in Scala 2.8 also supports all other methods on sequences. The ScalaDoc for class StringOps gives a complete list.
In particular, the splitAt
method comes in handly. Here's a REPL interaction which shows how.
scala> val ymd = "yyyyMMdd"
ymd: java.lang.String = yyyyMMdd
scala> val (y, md) = ymd splitAt 4
y: String = yyyy
md: String = MMdd
scala> val (m, d) = md splitAt 2
m: String = MM
d: String = dd
scala> y+"-"+m+"-"+d
res3: java.lang.String = yyyy-MM-dd
Just use the substring()
method on the string. Note that Scala strings behave like Java strings (with some extra methods), so anything that's in java.lang.String
can also be used on Scala strings.
val s = "20100903"
val t = s.substring(0, 4) // t will contain "2010"
(Note that the arguments are not length and starting index, but starting index (inclusive) and ending index (exclusive)).
But if this is about parsing dates, why don't you just use java.text.SimpleDateFormat
, like you would in Java?
val s = "20100903"
val fmt = new SimpleDateFormat("yyyyMMdd")
val date = fmt.parse(s) // will give you a java.util.Date object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With