首页 > 解决方案 > 如何将时间戳字符串转换为另一个时区的时间戳

问题描述

我有一个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中。我将如何做到这一点?

标签: javascala

解决方案


祖鲁时间

Z输入字符串末尾的 表示UTC 发音为“Zulu”。

ISO 8601

您的输入字符串采用标准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 ) ;

……和……</p>

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 ) ;

推荐阅读