我有从文件夹名称派生的字符串列表。
List(20170625, 20170625, 20170625, 20170625, 20170625, 20170625, 20170625, 20170625)
我想将整个元素列表转换为Local Date类型格式。我用Scala语言编写代码。任何人都可以帮助我吗?
答案 0 :(得分:2)
您可以尝试以下代码:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
val inputTimes = List(20170625, 20170625, 20170625, 20170625, 20170625, 20170625, 20170625, 20170625)
val dtf = DateTimeFormatter.ofPattern("yyyyMMdd")
val dates = inputTimes.map(date => LocalDate.parse(date.toString, dtf))
dates
您还可以指定新的区域设置
import java.time.LocalDate
import java.time.format.DateTimeFormatter
val inputTimes = List(20170625, 20170625, 20170625, 20170625, 20170625, 20170625, 20170625, 20170625)
val dtf = DateTimeFormatter.ofPattern("yyyyMMdd")
val dtfWithLocale = dtf.withLocale(java.util.Locale.US)
val dates = inputTimes.map(date => LocalDate.parse(date.toString, dtfWithLocale))
dates
结果是 dates
。
答案 1 :(得分:1)
如果您尝试将其转换为Undefined symbols for architecture x86_64:
"_PyUnicode_DecodeFSDefault", referenced from:
MainWindow::pythonTry(QString&) in mainwindow.o
格式,则可以执行此类操作
YYYY-MM-DD
答案 2 :(得分:0)
要将字符串转换为java.util.Date,您可以使用:
val df = new SimpleDateFormat("yyyyMMdd")
list.map(df.parse(_))
对于LocalDate使用
list.map(LocalDate.parse(_, DateTimeFormatter.ofPattern("yyyyMMdd")))
答案 3 :(得分:0)
分裂是粗略的实施。但是应该工作
def split(i: Int): LocalDate = {
val date = i % 100
val rem = i / 100
val mon = rem % 100
val r = rem / 100
LocalDate.of(r, mon, date)
}
def main(args: Array[String]): Unit = {
val l = List(20170625, 20170625, 20170625, 20170625, 20170625, 20170625, 20170625, 20170625)
val x = l.map(split)
}
答案 4 :(得分:0)
首先,我编写了将字符串转换为LocalDateTime格式的函数,如下所示
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
private def stringToDateTime(datetime:String): LocalDateTime ={
val pattern:String="yyyyMMdd"
LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern(pattern))}
然后我将值与List of elements映射如下
def mapDateTime(list:List[String]):List[LocalDateTime] ={
list.map(datetime => stringToDateTime(datetime))}
然后我最终得到以下结果
List[java.time.LocalDateTime] = List(2017-06-25, 2017-06-25, 2017-06-25, 2017-06-25, 2017-06-25, 2017-06-25, 2017-06-25, 2017-06-25)