我有一个 UTC 时间戳字符串
val x = "2018-09-26T15:05:19.1121042Z"
我想要一个这样的函数来将它转换为 CST 时区中的时间戳对象。
def StringToTimeStamp(str: String): Timestamp = {
val timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val timeZone = TimeZone.getTimeZone("America/Chicago")
timeFormat.setTimeZone(timeZone);
val now = timeFormat.format(str)
val ts = java.sql.Timestamp.valueOf(now)
ts
}
但是,我不知道SimpleDateFormat
我的字符串的格式,因为我不能输入像 T/Z 这样的字母,因为它们出现在我的字符串中x
。我将如何做到这一点?
在Z
您的输入字符串的结束意味着UTC,发音为“祖鲁”。
您的输入字符串采用标准ISO 8601格式。该java.time类解析或生成字符串时,在默认情况下使用这些标准格式。
Instant
将您的字符串解析为Instant
. Instant 表示 UTC 中的一个时刻,分辨率为纳秒。
Instant instant = Instant.parse("2018-09-26T15:05:19.1121042Z") ;
您的 JDBC 驱动程序可能能够接受Instant
。
myPreparedStatement.setObject( … , instant ) ;
OffsetDateTime
如果没有,您的 JDBC 4.2 或更高版本的驱动程序需要接受OffsetDateTime
.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
java.sql.Timestamp
如果您使用JDBC 4.2之前的旧JDBC 驱动程序,则回退到使用可怕的. 但是只有在绝对必要时才使用这些遗留的日期时间类,因为它们非常混乱。java.sql.Timestamp
您可以通过调用添加到旧类的新转换方法在现代类和遗留类之间进行转换。
java.sql.Timestamp ts = java.sql.Timestamp.from( instant ) ;
…和…
Instant instant = ts.toInstant() ;
大概你问的是java.sql.Timestamp
因为你正在与数据库交换值。
您所在的芝加哥时区与数据库工作无关,因为大多数数据库都以 UTC 时间存储。
ZonedDateTime
但是为了向用户展示,您可能需要从 UTC 调整到时区。
ZoneId z = ZoneId.of( "America/Chicago" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
生成本地化格式的字符串
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.US ) ;
String output = zdt.format( f ) ;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句