如何使用DateTimeFormatter将字符串转换为java.sql.Timestamp?
错误原因
你的时间字符串2020-08-03T20:15:49不包含时区或偏移量信息,而Instant.from()要求解析结果必须携带时区/偏移量字段才能完成转换,因此抛出对应报错。另外你的示例代码还存在变量名写错的问题:定义的时间变量是myTime,调用parse方法时传入了不存在的tempValue,实际运行时需要先修正这个变量名。
正确转换代码
有两种常用实现方案,根据你的使用习惯选择即可:
方案1:先解析为LocalDateTime再指定时区转Instant
import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; String myTime = "2020-08-03T20:15:49"; String myTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"; DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern(myTimeFormat); // 解析无时区信息的时间字符串为LocalDateTime LocalDateTime localDateTime = LocalDateTime.parse(myTime, timestampFormatter); // 指定时区完成转换,业务如果要求UTC时区可替换为 ZoneId.of("UTC") Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); Timestamp finalTime = Timestamp.from(instant);
方案2:给DateTimeFormatter绑定默认时区,直接解析为Instant
import java.sql.Timestamp; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; String myTime = "2020-08-03T20:15:49"; String myTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"; // 初始化格式化器时直接绑定默认时区 DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern(myTimeFormat) .withZone(ZoneId.systemDefault()); Instant instant = Instant.from(timestampFormatter.parse(myTime)); Timestamp finalTime = Timestamp.from(instant);
Spark UDF适配注意事项
你将该逻辑封装为UDF使用时,需要保证代码中指定的时区和Spark集群的SQL时区配置保持一致,避免出现时间值偏移问题。转换得到的java.sql.Timestamp完全匹配Spark Timestamp类型的schema要求,可以直接使用。
内容的提问来源于stack exchange,提问作者newbie
相关产品推荐
相关产品推荐

