java - 如何将时间戳字符串转换为另一个时区的时间戳
问题描述
我有一个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 ,发音为“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 ) ;
推荐阅读
- vb.net - 使用 Sub (VB) 在类之间传递字符串时收到“对象引用未设置为对象的实例”错误
- javascript - 如何使用 MuiThemeProvider 包装器和主题覆盖设置 MuiButton-outlined 的轮廓颜色和粗细?
- html - 从 HTML 生成的 MS Word 文档中不需要的方块
- firebase - 颤振:找不到正确的提供者
在此页面小部件上方 - laravel - 需要帮助来限制对某些 id 的路由访问
- python - 如何在函数内将参数声明为 datetime64?
- android - 如何在 Android 上旋转 SurfaceView?
- git - 使用 Git 中给定功能的文件夹结构打包修改/新文件
- html - 试图仅捕获图像名称而不是完整的图像路径
- tensorflow - 调用 dispose 后未知的遗留张量