java 转换 utc 时间,Java的:你如何转换UTC时间戳为本地时间?

该博客介绍了如何在Java中将UTC时间戳转换为本地时间,而不依赖于TimeZone.getTimeZone()这样的API调用。关键在于使用SimpleDateFormat设置时区,首先将时间戳解析为UTC,然后转换为目标时区,例如PST。示例代码演示了从'2012-08-15T22:56:02.038Z'到'2012-08-15T15:56:02.038Z'的转换过程。
摘要由CSDN通过智能技术生成

I have a timestamp that's in UTC and I want to convert it to local time without using an API call like TimeZone.getTimeZone("PST"). How exactly are you supposed to do this? I've been using the following code without much success:

private static final SimpleDateFormat mSegmentStartTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

Calendar calendar = Calendar.getInstance();

try {

calendar.setTime(mSegmentStartTimeFormatter.parse(startTime));

}

catch (ParseException e) {

e.printStackTrace();

}

return calendar.getTimeInMillis();

Sample input value: [2012-08-15T22:56:02.038Z]

should return the equivalent of [2012-08-15T15:56:02.038Z]

解决方案

Date has no timezone and internally stores in UTC. Only when a date is formatted is the timezone correction applies. When using a DateFormat, it defaults to the timezone of the JVM it's running in. Use setTimeZone to change it as necessary.

DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

Date date = utcFormat.parse("2012-08-15T22:56:02.038Z");

DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

pstFormat.setTimeZone(TimeZone.getTimeZone("PST"));

System.out.println(pstFormat.format(date));

This prints 2012-08-15T15:56:02.038

Note that I left out the 'Z' in the PST format as it indicates UTC. If you just went with Z then the output would be 2012-08-15T15:56:02.038-0700

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值