如何更改默认的 SQLite 时区

How can I change the default SQLite timezone

如何更改默认的 SQLite 时区?
插入记录时,我希望 SQlite 使用 +3:30 时区。

None of SQLite's supported date formats 包含时区。通常,日期假定为 UTC;没有 'default' 时区。

可以在 UTC 和本地时区之间转换日期值,或者为时间戳添加固定偏移量,但结果仍然没有时区标记,因此只有在以下情况下才应这样做将格式化时间戳以供显示。

要执行比 SQLite 支持更多的时区处理,您必须在应用程序的 Java 代码中进行处理。

正确,应该接受。

正如那里所说,您应该使用出色的 java.time 框架在 Java 代码中处理时区。

java.time

java.time classes are built into Java 8 and later. Much of their functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project, and further adapted to Android in the ThreeTenABP 项目。

java.time 类 是非常成功的 Joda-Time 库的继承者,这两个项目都由同一个人 Stephen Colbourne 领导。 java.time 类 取代了与 Java.

的最早版本捆绑在一起的臭名昭著的旧日期时间 类

UTC

最佳做法通常是在 UTC 中完成业务逻辑、数据存储和数据交换。大多数数据库以 UTC 格式存储日期时间。如前所述,SQLite(“精简版”)不支持时区,因此您应该将日期时间值调整为 UTC 以便插入到 SQLite 中。

出于这个原因和其他原因,程序员在工作时应该学会用 UTC 思考。

与 UTC 的偏移量

如果您确定要使用 +03:30 的偏移量,请使用 ZoneOffset and OffsetDateTime 类。顺便说一下,小时总是使用前导零,+03:30 而不是 +3:30;按照惯例很常见,并且是某些软件和协议所要求的。

ZoneOffset zoneOffset = ZoneOffset.of( 3 , 30 );
OffsetDateTime odt = OffsetDateTime.of( 2016 , 1 , 2 , 12 , 0 , 0 , 0 , zoneOffset );  // Noon on Jan 2 in offset `+03:30`.

时区

时区是 offset-from-UTC plus a set of rules of adjusting for anomalies such as Daylight Saving Time (DST)。如果您知道预期的时区,通常最好使用它而不是仅仅使用偏移量。例如,Asia/Tehran。使用 ZoneIdZonedDateTime

ZoneId zoneId = ZoneId.of( "Asia/Tehran" );
ZonedDateTime zdt = ZonedDateTime.of( 2016 , 1 , 2 , 12 , 0 , 0 , 0 , zoneId ); // Noon on Jan 2 in Iran.

Instant 为 UTC

为了与您一起工作,数据库切换到 UTC。 Instant 是 UTC 时间轴上的一个时刻,分辨率为纳秒。我们可以从上面讨论的任何一个日期时间对象中提取一个 Instant 对象。

Instant instant = odt.toInstant();  
Instant instant = zdt.toInstant();  

JDBC

如果您的 JDBC 驱动程序符合 JDBC 4.2 (JSR 221, Guide, java.sql package), you may be able to use the Instant object directly by passing to setObject on your PreparedStatement.

myPreparedStatement.setObject( instant , 1 );

如果这不适用于您的 JDBC 驱动程序,请回退到使用旧的 java.sql 类型。对于日期时间,这意味着 java.sql.Timestamp and its from( Instant ) 方法。

java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
myPreparedStatement.setTimestamp( ts , 1 );