如何在java中将时间戳字符串转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29256499/
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
How to converted timestamp string to a date in java
提问by Rajeev
I have a string "1427241600000" and I want it converted to "yyyy-MM-dd" format.
我有一个字符串“1427241600000”,我希望它转换为“yyyy-MM-dd”格式。
I have tried, but I am not able to parse it, please review the below code
我试过了,但我无法解析它,请查看下面的代码
try {
String str = "1427241600000";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Date date =sf.parse(str);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
I would like to know where I went wrong.
我想知道我哪里出错了。
回答by Flown
You should try it the other way around. First get the Date out of the milliTime and then format it.
你应该反过来试试。首先从毫秒中获取日期,然后对其进行格式化。
String str = "1427241600000";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(Long.parseLong(str));
System.out.println(sf.format(date));
回答by Manish Kothari
Use Date date =new Date(Long.parseLong(str));
to convert your String to Date object.
使用Date date =new Date(Long.parseLong(str));
你的字符串转换为Date对象。
if you are using SimpleDateFormat()
the format specified as a parameter to this function should match the format of the date in the String (str in your case). In your case yyyy-MM-dd
does not match the format of the time stamp (1427241600000).
如果您使用SimpleDateFormat()
指定为该函数的参数的格式,则应与字符串中日期的格式(在您的情况下为 str )相匹配。在您的情况下yyyy-MM-dd
与时间戳的格式不匹配(1427241600000)。
回答by Paul
the conversion is highly dependent on what format the timestamp is in. But i assume the whole thing should actually be a long
and is simply the systemtime from when the timestamp was created. So this should work:
转换高度依赖于时间戳的格式。但我认为整个事情实际上应该是一个long
并且只是创建时间戳时的系统时间。所以这应该有效:
String str = ...;
Date date = new Date(Long.parseLong(str));
回答by GopinathSk
You can do it like this:
你可以这样做:
use a SimpleDateFormat with an appropriate format string (be careful to use the correct format letters, uppercase and lowercase have different meanings!).
使用带有适当格式字符串的 SimpleDateFormat(注意使用正确的格式字母,大写和小写有不同的含义!)。
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");