java-UTC时间戳格式化成年月日,UTC时间戳转成北京时间并格式化年月日(亲测)

java-UTC时间戳格式化北京时间
一、时间戳定义
二、应用场景
三、总结
一、时间戳定义
1、UTC时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总秒数
2、北京时间戳是指1970年01月01日08时00分00秒起至现在的总秒数

由此可知:北京时间 = UTC时间+8小时
1
2
3
4
二、应用场景
1、1641537092表示的是UTC时间戳,格式化成年月日时分秒。
解释:如下代码,我认为无论是UTC时间戳还是北京时间戳 格式化成年月日,只需要下面代码就行了,实际是错误的。

Long unixtimestamp = 1641537092L;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format1 = simpleDateFormat.format(new Date(unixtimestamp * 1000));
System.out.println(format1);//2022-01-07 14:31:32
1
2
3
4
正确写法:

Long unixtimestamp = 1641537092L;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String format1 = simpleDateFormat.format(new Date(unixtimestamp * 1000));
System.out.println(format1);//2022-01-07 06:31:32
1
2
3
4
5
2、1641537092表示的是UTC时间戳,格式化成北京时间并转成年月日的形式。下面两种方式均可实现:
/**
* 方式1
* 注:默认使用的是北京时区,无论是UTC时间戳还是北京时间戳,格式化后都是北京时间。
*/
Long unixtimestamp = 1641537092L;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format1 = simpleDateFormat.format(new Date(unixtimestamp * 1000));
System.out.println(format1);//2022-01-07 14:31:32
1
2
3
4
5
6
7
8
/**
* 方式2
* 注:时间戳+8小时,格式化时指定UTC时区, 格式化后是北京时间。
*/
Long unixtimestamp = 1641537092L + 8*60*60;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String format1 = simpleDateFormat.format(new Date(unixtimestamp * 1000));
System.out.println(format1);//2022-01-07 14:31:32
1
2
3
4
5
6
7
8
9
三、总结
UTC时间戳转北京时间有两种方法
1、直接把UTC时间戳格式化成年月日,格式化时不设置时区,因为默认是北京时区。
2、把UTC时间戳加8小时后,格式化时区需要设置成UTC时区。
3、UTC时间 = 北京时间+8小时,转换的时候,一定要注意当前时区

注意:如果您理解不了这个概念,就按照我给的上面的例子,直接套用就行了,慢慢品!!!
————————————————
版权声明:本文为CSDN博主「北漂IT民工_程序员」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_41919486/article/details/122428892

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值