这个问题在这里已有答案:
Java:来自unix时间戳的日期 8个答案我的TimeStamp时间为String 1374160160 ,相当于1374160160 07/18/2013 。
如果有办法如何将此TimeStamp转换为July 18, 2013格式的日期?
这是我的代码片段:
try{ String timeStamp = "1374160160"; DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); Date netDate = (new Date(timeStamp)); return sdf.format(netDate); } catch(Exception ex) { return ""; }它总是返回01/17/1970为什么?
第二个问题是不推荐使用new Date(String) 。
总结一下:
如何从时间戳创建正常日期( July 18, 2013 )并避免使用已弃用的方法?
This question already has an answer here:
Java: Date from unix timestamp 8 answersI have TimeStamp time as String 1374160160 which is equivalent 07/18/2013.
If there is a way how I can convert this TimeStamp to date with format July 18, 2013 ?
This is my code snippet:
try{ String timeStamp = "1374160160"; DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); Date netDate = (new Date(timeStamp)); return sdf.format(netDate); } catch(Exception ex) { return ""; }It always returns 01/17/1970 why?
The second problem is that new Date(String) is deprecated.
To sum up:
How to create normal date (July 18, 2013) from time-stamp and avoid the deprecated methods ?
最满意答案
您的timeStamp实例保持秒,但Java Date构造函数需要毫秒。 通过文档 :
分配一个Date对象并对其进行初始化,以表示自标准基准时间称为“epoch”以来的指定毫秒数,即1970年1月1日00:00:00 GMT
所以你应该使用这个:
String timeStamp = "1374160160"; long timeMillis = Long.valueOf(timeStamp) * 1000; Date netDate = new Date(timeMillis);代替:
String timeStamp = "1374160160"; Date netDate = (new Date(timeStamp));Your timeStamp instance holds seconds but Java Date constructor expects milliseconds. Via documentation:
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT
So you should use this:
String timeStamp = "1374160160"; long timeMillis = Long.valueOf(timeStamp) * 1000; Date netDate = new Date(timeMillis);instead of:
String timeStamp = "1374160160"; Date netDate = (new Date(timeStamp));更多推荐
发布评论