从时间戳到正常日期[重复](From timestamp to normal date [duplicate])

编程入门 行业动态 更新时间:2024-10-26 10:35:38
从时间戳到正常日期[重复](From timestamp to normal date [duplicate])

这个问题在这里已有答案:

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 answers

I 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));

更多推荐

本文发布于:2023-08-07 03:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461190.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   时间   timestamp   duplicate   date

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!