且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中将Unix时间戳转换为日期

更新时间:2023-01-22 12:02:33

您可以使用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)