Scala string to date conversion

淺唱寂寞╮ 提交于 2020-06-26 14:41:34

问题


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)}")
}

回答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)



来源:https://stackoverflow.com/questions/62461428/scala-string-to-date-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!