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

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

问题描述

如何在Java中将Unix时间戳记中的分钟转换为日期和时间?例如,时间戳记 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 .

实际上,我希望它是根据美国格林尼治标准时间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 所采用的模式非常灵活,您可以根据给定的特定 Date 日期,根据所编写的模式,在javadocs中检入可用于产生不同格式的所有变体.代码>. 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天全站免登陆