如何将时间戳字符串转换为另一个时区中的时间戳

时间:2018-09-26 15:16:58

标签: java scala

我在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格式,因为我不能像出现在我的字符串x中的字母那样输入T / Z之类的字母。我将如何完成?

1 个答案:

答案 0 :(得分:3)

祖鲁时间

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

ISO 8601

您的输入字符串为标准ISO 8601格式。在解析或生成字符串时, java.time 类默认使用这些标准格式。

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 driver之前使用较旧的JDBC 4.2,则退而使用可怕的java.sql.Timestamp。但是,仅在绝对必要时才使用这些旧式日期时间类,因为它们太糟了。

您可以通过调用添加到旧类中的新转换方法,在新旧类之间进行转换。

java.sql.Timestamp ts = java.sql.Timestamp.from( instant ) ;

…和…

Instant instant = ts.toInstant() ;

时区

大概是您在询问java.sql.Timestamp,因为您正在与数据库交换值。

您的time zone of Chicago与数据库工作无关,因为大多数数据库都在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 ) ;
相关问题