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

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

问题描述

如何在Unix中将分钟从unix时间戳转换为日期和时间。例如,时间戳 1372339860 对应星期四,2013年6月27日13:31:00 GMT

How can I convert minutes from unix time stamp to date and time in java. For example, time stamp 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

Edit : 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中检查所有可用于根据您在给定特定日期时编写的模式生成不同格式的变体。 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


  • 因为日期提供了一个 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天全站免登陆