【发布时间】:2021-11-14 01:15:05
【问题描述】:
我在字符串中有一个时间戳,我正在使用 DateTimeFormatter 解析字符串,如下所示并将其分配给时间戳类型变量
import java.sql.Timestamp
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
import java.time.Instant
String myTime = "2020-08-03T20:15:49"
String myTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"
DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern(myTimeFormat);
TemporalAccessor ta = timestampFormatter.parse(tempValue);
// getting error that Cannot create Instant from java.time.format.Parsed
Timestamp finalTime = Timestamp.from(Instant.from(ta));
如何将其转换为 java.sql.Timestamp?
上下文:我正在尝试将 spark 数据帧中的字符串列(使用时间戳格式)转换为时间戳列,并且我在我的 udf 中使用上述逻辑(使用 udf,因为我还需要执行其他检查只是强制转换),因此尝试转换为 Timestamp 以将此列作为 Timestamp 应用 spark 模式
参考:https://spark.apache.org/docs/latest/sql-ref-datatypes.html
【问题讨论】:
-
我建议你不要使用
java.sql.Timestamp。该课程设计不良且早已过时。由于 JDBC 4.2 将LocalDateTime从 java.time, the modern Java date and time API 传递到您的 SQL 数据库。
标签: java apache-spark-sql timestamp datetime-format java-time