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

I have date and time in separate fields, in yyyyMMdd and HHmmss formats respectively. To parse them, I think, to build the string yyyy-MM-ddTHH: mm: ss and pass this to the joda-time constructor. So I am looking to get the 1st 4 digits, then 2 digits, starting at index 5, etc. How to do it? List.fromString (String) (which I found here ) seems to be broken.

+3
source share
4 answers

Just use the method substring()on the line. Note that Scala strings behave like Java strings (with some additional methods), therefore everything that java.lang.Stringcan also be used in Scala strings.

val s = "20100903"
val t = s.substring(0, 4) // t will contain "2010"

(Note that the arguments are not the length and the starting index, but the starting index (inclusive) and the ending index (exclusive)).

But when it comes to date parsing, why don't you just use java.text.SimpleDateFormatit like in Java?

val s = "20100903"
val fmt = new SimpleDateFormat("yyyyMMdd")
val date = fmt.parse(s)  // will give you a java.util.Date object
+8
source

The method substringcan certainly get you there, but String in Scala 2.8 also supports all the other methods in the sequences. ScalaDoc for the StringOps class gives a complete list.

, splitAt . REPL, , .

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
+15

If you use Joda Time, you can use

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

For a more general problem of parsing such strings, it is useful to use Regex (although I would not 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
+7
source
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+ ...
+2
source

Source: https://habr.com/ru/post/1763030/


All Articles