在java中将unix时间戳转换为日期 [英] Convert unix timestamp to date in java

查看:94
本文介绍了在java中将unix时间戳转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将分钟从 Unix 时间戳转换为 Java 中的日期和时间?例如,时间戳 1372339860 对应于 Thu, 27 Jun 2013 13:31:00 GMT.

How can I convert minutes from Unix timestamp to date and time in java? For example, timestamp 1372339860 correspond to Thu, 27 Jun 2013 13:31:00 GMT.

我想将 1372339860 转换为 2013-06-27 13:31:00 GMT.

实际上我希望它是根据美国时间 GMT-4,所以它会是 2013-06-27 09:31:00.

Actually I want it to be according to US timing GMT-4, so it will be 2013-06-27 09:31:00.

推荐答案

您可以使用 SimlpeDateFormat 像这样设置日期格式:

You can use SimlpeDateFormat to format your date like this:

long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L); 
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

SimpleDateFormat 采用的模式如果非常灵活,您可以在 javadocs 中检查所有可用于根据给定特定 Date 编写的模式生成不同格式的变体代码>.http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  • 因为 Date 提供了一个 getTime() 方法来返回自 EPOC 以来的毫秒数,所以你需要给 SimpleDateFormat 一个时区根据您的时区正确格式化日期,否则它将使用 JVM 的默认时区(如果配置良好,无论如何都是正确的)
  • Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)

这篇关于在java中将unix时间戳转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆