如何将字符串时间戳转换为具有特定时区的时间戳

时间:2021-03-26 07:10:54

标签: java timestamp timestamp-with-timezone sql-timestamp

我正在尝试将包含时区的字符串时间戳转换为具有相同时区的时间戳。但是,在执行下面的代码时,我得到了默认的系统时间戳。有人可以帮我解决这个问题。下面是我正在尝试的代码。

try {
    Date dt = new Date();
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    String dateString = f.format(dt);
    System.out.println("DateString: "+dateString);
    Date parsedDate = f.parse(dateString);
    System.out.println("ParsedDate: "+parsedDate);
    Timestamp timestamp = new Timestamp(parsedDate.getTime());
    System.out.println("Timestamp: "+timestamp);
    
}catch (Exception e) {
    // TODO: handle exception
}

执行上述代码时,我得到以下结果:

DateString: 2021-03-26T06:57:05.982+0000
ParsedDate: Fri Mar 26 12:27:05 IST 2021
Timestamp: 2021-03-26 12:27:05.982

但我必须将时间戳输出为 2021-03-26T06:57:05.982+0000

2 个答案:

答案 0 :(得分:1)

您使用 java.time 类的代码:

        ZonedDateTime zdt = ZonedDateTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        DateTimeFormatter dfGMT = df.withZone(ZoneId.of("GMT"));
        
        String dateString = dfGMT.format(zdt);
        System.out.println("DateString: "+dateString);
        
        ZonedDateTime parsedDate = ZonedDateTime.parse(dateString,dfGMT);
        System.out.println("ParsedDate: "+ parsedDate);
        Timestamp timestamp = Timestamp.from(parsedDate.toInstant());
        System.out.println("Zoned Timestamp: "+timestamp);
        
        //ignoring zone info from date string
        LocalDateTime ldt = LocalDateTime.from(dfGMT.parse(dateString));
        timestamp = Timestamp.valueOf(ldt);
        System.out.println("Zone stripped GMT timestamp: "+timestamp);
        
        
        ZonedDateTime zdt1 = ldt.atZone(ZoneId.of("GMT"));
        zdt1 = zdt1.withZoneSameInstant(ZoneId.of("America/Chicago"));
        timestamp = Timestamp.valueOf(zdt1.toLocalDateTime());
        System.out.println("Zone stripped CST timestamp: "+timestamp);

输出:

DateString: 2021-03-26T09:10:37.537+0000
ParsedDate: 2021-03-26T09:10:37.537Z[GMT]
Zoned Timestamp: 2021-03-26 14:40:37.537
Zone stripped GMT timestamp: 2021-03-26 09:10:37.537
Zone stripped CST timestamp: 2021-03-26 04:10:37.537

答案 1 :(得分:0)

java.time 和 JDBC 4.2

您不需要任何格式化、解析或转换。将当前时间戳插入到您的 SQL 数据库中:

    OffsetDateTime currentTimestamp = OffsetDateTime.now(ZoneOffset.UTC);
    String sql = "insert into your_table(your_timestamp_with_time_zone_column) values (?);";
    try (PreparedStatement prepStmt = yourDatabaseConnection.prepareStatement(sql)) {
        prepStmt.setObject(1, currentTimestamp);
        prepStmt.executeUpdate();
    }
相关问题