Scala字符串到日期的转换 [英] Scala string to date conversion

查看:521
本文介绍了Scala字符串到日期的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有日期的字符串格式,但来自csv文件:
20200520T0200,假设其格式为(yyyyMMdd / T / 24小时格式)。

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文件中的行并将其分隔到arraybuffer中。

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

我的问题是我无法将字符串格式化为日期,因为我需要使用日期来计算一些值。因为我将使用此格式化程序来格式化我的arraybuffer第一个元素的所有值,这是字符串 20200406T0300等,等等,等等的时间。

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".

目前,我已经尝试使用DateTimeFormatter,

Currently i have tried using DateTimeFormatter,

csv文件
导入java.io.File

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


推荐答案

我不认为这是标准的DateTime格式,有人删除或添加了一些东西。看起来像 ISO日期,但 ISO 的格式为 yyyy-MM-ddTHH:mm。 ..

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 ...

编辑:@ OleV.V。请明确将该格式作为 ISO 8601 格式

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

您有一些选择


  1. 要么删除该T,然后使用 SimpleDateTimeFormat进行解析

val格式= new SimpleDateFormat( yyyyMMddHHmm)
val f = format.parse( 20200520T0200&。replaceAll( T, ")))//格林尼治标准时间2020年5月20日星期二02:00:00

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

或定义自定义格式器并将其解析为曾经 时间对象 使您的船漂浮起来。

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)

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

这篇关于Scala字符串到日期的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆