Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将Java中的时间戳数据类型转换为JPA实体Java中的UTC时区?_Java_Jpa_Timestamp_Timezone_Utc - Fatal编程技术网

如何将Java中的时间戳数据类型转换为JPA实体Java中的UTC时区?

如何将Java中的时间戳数据类型转换为JPA实体Java中的UTC时区?,java,jpa,timestamp,timezone,utc,Java,Jpa,Timestamp,Timezone,Utc,我们使用PO类来表示sql DB,并使用Java JPA实体。在该类中,我们有一列作为字段currentTime,带有时间戳数据类型和JPA的@version注释 @Version private Timestamp currentTime; 无论何时更新实体,currentTime都会使用最新时间更新 currentTime = new Timestamp(0); //this will create the new timestamp with current time. 但它目前占用了

我们使用PO类来表示sql DB,并使用Java JPA实体。在该类中,我们有一列作为字段
currentTime
,带有时间戳数据类型和JPA的
@version
注释

@Version
private Timestamp currentTime;
无论何时更新实体,currentTime都会使用最新时间更新

currentTime = new Timestamp(0); //this will create the new timestamp with current time.
但它目前占用了服务器的时间。在保存到DB之前,我想将此时间转换为UTC格式

任何人都可以帮助我如何将时间转换为UTC时间?

请尝试以下代码

currentTime = Timestamp.valueOf(LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC));

当我需要解析来自服务器的时间时,我也遇到了类似的问题,但在将此信息存储到MySQL DB之前,我需要将此时间转换为UTC格式。这就是我的解决方案:

     Instant dateConverted = LocalDateTime
                            .parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH))
                            .atZone(ZoneId.of("Europe/Bratislava")).toInstant();

     long epochTime = dateConverted.toEpochMilli() / 1000L;
其中,dateTime是一个字符串变量,包含来自服务器的日期和时间 我使用DateTimeFormatter将我的时间格式化为适当的格式。 最后,我添加了时区的zoneID并将其转换为Instant


最后我转换成秒

Java的时间戳默认为UTC,不是吗?不,它默认占用服务器时间谢谢你的回答。但是我需要将带有@Version注释的时间戳转换为UTC时区请不要教年轻人使用过时且臭名昭著的
SimpleDataFormat
类。至少不是第一个选择。而且不是毫无保留的。今天,我们有了更好的in及其
DateTimeFormatter
。谢谢simon。但是Instant和LocalDateTime类是不可访问的,你能告诉我为什么它们不可访问吗?您是否需要为它们执行静态导入,或者您的项目不允许使用这些类?@sherinshaf这是您的Java版本?谢谢。但是我的项目无法访问Instant和LocalDateTime请参考
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
       sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String localTime = sdf.format(new Date(your_time_stamp));
    Date date = new Date();
    try {
        date = sdf.parse(localTime);//get local date
    } catch (ParseException e) {
        e.printStackTrace();
    }