将纪元字符串转换为 Java 日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20411782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert epoch String to Java date
提问by Pi Horse
I am getting an epoch String from my DB which looks something like this : 1391328000000
我从我的数据库中得到一个纪元字符串,它看起来像这样:1391328000000
I am having a hard time trying to convert it to Java Date.
我很难将其转换为 Java 日期。
I tried the following :
我尝试了以下方法:
private String buildDate(String dateString){
System.out.println("dateString " + dateString);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(Integer.parseInt(dateString));
return formatted;
}
采纳答案by Andrei Nicusan
I think you're overthinking about the DateFormat
. If I want to simply obtain a Date
instance, what I would try is the following:
我认为你对DateFormat
. 如果我只想获取一个Date
实例,我会尝试以下内容:
Date d = new Date(Long.parseLong(dateString));
回答by Daniel Martin
You need to turn it into a java.util.Date
object in order for SimpleDateFormat
to handle it. Also, a value like what you quoted needs to be parsed as a long
, as it is too large for an int
.
你需要把它变成一个java.util.Date
对象才能SimpleDateFormat
处理它。此外,您引用的值需要解析为 a long
,因为它对于int
.
That is, change the line where you set formatted
to be:
也就是说,更改您设置的行formatted
:
String formatted = format.format(new Date(Long.parseLong(dateString)));
As an aside, if the project you're working on can handle an extra external dependency, switch date/time handling over to the joda library. The stuff in java.util
(that is, Date
and Calendar
) rapidly becomes painful and error-prone to work with.
顺便说一句,如果您正在处理的项目可以处理额外的外部依赖项,请将日期/时间处理切换到joda 库。在东西java.util
(即Date
和Calendar
)迅速变得痛苦且容易出错与工作。