简体   繁体   English

Scala 字符串到日期的转换

[英]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).我有一个日期的字符串格式,但它来自 csv 文件:20200520T0200,假设其格式为(yyyyMMdd/T/24 小时格式)。

I have managed to read the lines in the csv file and seperated it into an arraybuffer.我设法读取了 csv 文件中的行并将其分离到一个数组缓冲区中。

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".因为我将使用这个格式化程序来格式化我的arraybuffer的第一个元素的所有值,这是带有“20200406T0300等”字符串的时间。

Currently i have tried using DateTimeFormatter,目前我已经尝试使用 DateTimeFormatter,

csv file import java.io.File csv 文件导入 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.我不认为这是标准的 DateTime 格式,有人删除或添加了一些东西。 It looks like ISO DATE but ISO is in format yyyy-MM-ddTHH:mm...它看起来像ISO DATEISO格式为yyyy-MM-ddTHH:mm...

Edit: @OleV.V.编辑:@OleV.V。 kindly clarified the format as the basic form of ISO 8601 format请澄清格式为ISO 8601格式的基本格式

You have a few options你有几个选择

  1. Either get rid of that T and parse it with SimpleDateTimeFormat要么摆脱那个 T 并用SimpleDateTimeFormat解析它

    val format = new SimpleDateFormat("yyyyMMddHHmm") val f = format.parse("20200520T0200".replaceAll("T", "")) //Wed May 20 02:00:00 GMT 2020 val format = new SimpleDateFormat("yyyyMMddHHmm") val f = format.parse("20200520T0200".replaceAll("T", "")) //2020 年 5 月 20 日星期三 02:00:00 GMT

  2. Or define a custom formatter and parse it into what ever time object floats your boat.或者定义一个自定义格式化程序并将其解析为time object

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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