java gettime换算小时,如何在Java中将UTC时间戳转换为本地日期,小时,分钟?

这篇博客介绍了如何在Java中使用`java.util.Calendar`类将UNIX时间戳转换成本地时区的年、日、小时和分钟值。通过设置时区并利用`getTimeInMillis()`方法,可以将时间戳转换为日期对象,然后使用`SimpleDateFormat`格式化日期字符串。示例代码展示了具体的实现步骤,并给出了在GMT-4时区的输出结果。
摘要由CSDN通过智能技术生成

Given then timestamp 1245613885 that is a timestamp in GMT

How do I turn that into Year, Day, Hour, Minute values in Java using the server's local timezone info?

解决方案

You can use java.util.Calendar for this. It offers a setTimeZone() method (which is by the way superfluous since it by default already picks the system default timezone).

long timestamp = 1245613885;

Calendar calendar = Calendar.getInstance();

calendar.setTimeZone(TimeZone.getDefault());

calendar.setTimeInMillis(timestamp * 1000);

int year = calendar.get(Calendar.YEAR);

int day = calendar.get(Calendar.DATE);

int hour = calendar.get(Calendar.HOUR_OF_DAY);

int minute = calendar.get(Calendar.MINUTE);

If you'd like to present it in a human readable date string, then I'd suggest SimpleDateFormat for this.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dateString = sdf.format(calendar.getTime());

System.out.println(dateString); // 2009-06-21 15:51:25

(the output is correct as per my timezone GMT-4)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值