简体   繁体   中英

Scala string to date conversion

I have a string format of a date but which is from a csv file: 20200520T0200, assuming its in the format of (yyyyMMdd/T/24-hour format).

I have managed to read the lines in the csv file and seperated it into an arraybuffer.

My question is i cannot format the string into a date, as i need to use the date to calculate some values. As i will use this formatter to format all the values of the first element of my arraybuffer which is the time with strings of "20200406T0300, etc, etc, etc".

Currently i have tried using DateTimeFormatter,

csv file import java.io.File

import scala.io.Source
import scala.collection.mutable.ArrayBuffer
import java.time._
import java.time.format.DateTimeFormatter

val dtf = DateTimeFormatter.ofPattern("yyyyMMddaH")
val date_int_format = DateTimeFormatter.ofPattern("yyyyMMdd")
val last_extract_value= "20200530T0200"
val string_to_date = dtf.parse(last_extract_value)


val rows = ArrayBuffer[Array[String]]()

val bufferedSource = Source.fromFile("D:/Scala/Testtt/src/main/scala/testData.csv")
for (line <- bufferedSource.getLines.drop(10)) {
  rows += line.split(",").map(_.trim)

}
for (row <- rows) {
  println(s"${row(0)}|${row(1)}")
}

I don't think that's a standard DateTime format, someone either removed or added something to it. It looks like ISO DATE but ISO is in format yyyy-MM-ddTHH:mm...

Edit: @OleV.V. kindly clarified the format as the basic form of ISO 8601 format

You have a few options

  1. Either get rid of that T and parse it with SimpleDateTimeFormat

    val format = new SimpleDateFormat("yyyyMMddHHmm") val f = format.parse("20200520T0200".replaceAll("T", "")) //Wed May 20 02:00:00 GMT 2020

  2. Or define a custom formatter and parse it into what ever time object floats your boat.

    val customFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmm"); val q = LocalDateTime.parse("20200520T0200", customFormatter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM