我必须在UTC中存储UTC dateTime.
我已将特定时区中给出的dateTime转换为UTC.因为我遵循以下代码.
我的输入日期时间是"20121225 10:00:00 Z"时区是"亚洲/加尔各答"
我的服务器/数据库(oracle)在同一时区(IST)"亚洲/加尔各答"运行
获取此特定时区中的Date对象
String date = "20121225 10:00:00 Z";
String timeZoneId = "Asia/Calcutta";
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
DateFormat dateFormatLocal = new SimpleDateFormat("yyyyMMdd HH:mm:ss z");
//This date object is given time and given timezone
java.util.Date parsedDate = dateFormatLocal.parse(date + " "
+ timeZone.getDisplayName(false, TimeZone.SHORT));
if (timeZone.inDaylightTime(parsedDate)) {
// We need to re-parse because we don't know if the date
// is DST until it is parsed...
parsedDate = dateFormatLocal.parse(date + " "
+ timeZone.getDisplayName(true, TimeZone.SHORT));
} …Run Code Online (Sandbox Code Playgroud) 我在PostgreSQL中创建了一个这样的表:
create table myTable (
dateAdded timestamp(0) without time zone null default (current_timestamp at time zone 'UTC');
)
Run Code Online (Sandbox Code Playgroud)
我选择"没有时区",因为我知道我的应用程序使用的所有时间戳都是 UTC.据我所知,"带时间戳"的唯一区别是我可以在其他时区提供值,然后转换为UTC.但是,我想避免这种自动转换,因为如果我知道我的值是UTC,它们几乎没有任何好处.
当我在测试表中添加新记录并使用pgAdmin查看表的内容时,我可以看到插入日期已经以UTC格式正确保存.
但是,当我尝试使用JDBC选择值时,该值减去2小时.我位于UTC + 2,因此看起来JDBC假定表中的日期不是UTC时间戳,而是UTC + 2时间戳而是尝试转换为UTC.
一些谷歌搜索显示,JDBC标准规定了与当前时区的转换,但是可以通过向getTimestamp/setTimestamp调用提供Calander来防止这种情况.但是提供日历并没有任何差别.这是我的MyBatis/Jodatime转换器:
@MappedTypes(DateTime.class)
public class DateTimeTypeHandler extends BaseTypeHandler<DateTime> {
private static final Calendar UTC_CALENDAR = Calendar.getInstance(DateTimeZone.UTC.toTimeZone());
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
DateTime parameter, JdbcType jdbcType) throws SQLException {
ps.setTimestamp(i, new Timestamp(parameter.getMillis()), UTC_CALENDAR);
}
@Override
public DateTime getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return fromSQLTimestamp(rs.getTimestamp(columnName, UTC_CALENDAR));
}
/* further get methods with …Run Code Online (Sandbox Code Playgroud) 我想将时间戳保存到数据库,而不是由jdbc驱动程序转换为本地时区.目前只有MySQL和PostgreSQL对我很重要,但如果有一个独立于数据库的解决方案,我将不胜感激.
例:
// i want that to be saved as 1970-01-01 00:00:00
TimeStamp ts = new java.sql.Timestamp(0);
// gets transformed to local time by jdbc driver (in my case to 1970-01-01 01:00:00)
st.setTimestamp(0, new java.sql.Timestamp(0));
// only works using postgres (mysql connector seems to ignore the calendar)
// postgres => 1970-01-01 00:00:00
// mysql => 1970-01-01 01:00:0
Calendar calutc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
st.setTimestamp(0, new java.sql.Timestamp(0), utccal);
Run Code Online (Sandbox Code Playgroud)
我已经尝试计算一个时间戳值,该值被转换为正确的值(例如-3600000 => 1970-01-01 00:00:00在我的时区)但这对于当天日期的postgres不起作用节约时间的变化.