开发者

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 construc开发者_运维百科t 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're using Joda Time, you should be able to use

val date = DateTimeFormat.forPattern("yyyyMMdd, HHmmss")
                         .parseDateTime(field1 + ", " + field2)

For the more general problem of parsing Strings like this, it can be helpful to use a Regex (although I wouldn't recommend it in this case):

scala> val Date = "(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)".r
Date: scala.util.matching.Regex = (\d\d\d\d)(\d\d)(\d\d)

scala> "20100903" match { 
     |    case Date(year, month, day) => year + "-" + month + "-" + day 
     | }
res1: java.lang.String = 2010-09-03


val field1="20100903"
val field2="100925"
val year = field1.substring(1,5)
val month = field1.substring(5,7)
val day = ...
...
val toYodaTime = year + "-" + month+"-"+day+ ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜