Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala 2.8, how to access a substring by its length and starting index?

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.

like image 501
Ivan Avatar asked Nov 28 '22 05:11

Ivan


2 Answers

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
like image 90
Martin Odersky Avatar answered May 18 '23 14:05

Martin Odersky


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
like image 35
Jesper Avatar answered May 18 '23 15:05

Jesper