【随手记】Java将时间戳转为RFC3339标准时间格式

如题所示,将时间戳转为RFC3339标准时间格式,主要用于微信支付V3

直接上代码:

    public static String timeStampToRfc3339(long timeStamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String formatDate = simpleDateFormat.format(new Date(timeStamp));
        return formatDate;
    }

注意:这里的T需要加单引号,不然会报错,+0800的+号不需要体现在时间格式中,会自动加上去的。

测试代码:

    public static void main(String[] args) {
        System.out.println(timeStampToRfc3339(System.currentTimeMillis()));
    }

结果:2021-01-26T13:52:01+0800

=============== 2024.2.22更新 ===============

据网友反馈,正确的格式是:

yyyy-MM-dd'T'HH:mm:ssXXX

2021年的博客了,当时自己也没看清楚结果,不好意思。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
可以Java中的`java.time`包中的类和方法来将时间戳转换为本地时区的时间。以下是一个示例: ```java import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class TimestampToLocalTime { public static void main(String[] args) { long timestamp = 1630602257000L; // 时间戳,单位是毫秒 Instant instant = Instant.ofEpochMilli(timestamp); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String localTime = localDateTime.format(formatter); System.out.println("本地时间:" + localTime); } } ``` 解释一下代码: 1. 将时间戳转换为`Instant`对象:`Instant instant = Instant.ofEpochMilli(timestamp);` 2. 将`Instant`对象转换为本地时区的`LocalDateTime`对象:`LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());` 3. 定义一个日期时间格式:`DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");` 4. 将`LocalDateTime`对象按照指定的日期时间格式转换为字符串:`String localTime = localDateTime.format(formatter);` 5. 打印本地时间:`System.out.println("本地时间:" + localTime);` 在上述代码中,`ZoneId.systemDefault()`方法返回的是本地时区的`ZoneId`对象,可以根据需要更改为其他时区的`ZoneId`对象来得到相应时区的时间
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值