Java 将时间戳转换为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6369731/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:24:19  来源:igfitidea点击:

convert timestamp to date

javaandroiddatetime

提问by TechnocraT

I'm getting the date from an sms message in android as a time stamp in seconds or milliseconds from epoch.I need to display it as standard date and time using java.

我从 android 中的 sms 消息中获取日期作为时间戳(以秒或毫秒为单位)。我需要使用 java 将其显示为标准日期和时间。

int date      = (cursor.getColumnIndex(SmsReceiver.DATE));

this returns some number like 1308114404722.

这将返回一些数字,如 1308114404722。

what is the process to use this number and display as current date

使用此数字并显示为当前日期的过程是什么

采纳答案by Jesper

int date = ...
Date dateObj = new Date(date);

To format a Dateobject, use for example SimpleDateFormat:

要格式化Date对象,请使用例如SimpleDateFormat

DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String text = df.format(dateObj);

Also, you should store number-of-milliseconds-since-epoch values in a long, not in an int, because an intis not large enough. (In fact, the number 1308114404722 doesn't even fit in a 32-bit int).

此外,您应该将 number-of-milliseconds-since-epoch 值存储在 a 中long,而不是 an 中int,因为 anint不够大。(实际上,数字 1308114404722 甚至不适合 32 位int)。

回答by Plamen Nikolov


SimpleDateFormat formatter = new SimpleDateFormat("HH:mm dd.MM.yyyy");
Date date = new Date(1308114404722);
Calendar cal = Calendar.getInstance();
cal.setTime(date);

回答by Mark Allison

Try:

尝试:

DateFormat df = DateFormat.getInstance();
String dateStr = df.format( new Date( date ) );

回答by ReNa

I suppose that this is Epoch Timestamp to convert it to human readable form use

我想这是 Epoch Timestamp 将其转换为人类可读的形式使用

int date = (cursor.getColumnIndex(SmsReceiver.DATE));
String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (date*1000));

hopefully this will work as on converting this value: 1308114404722

希望这将在转换此值时起作用1308114404722

the time comes to be Wed, 15 Jun 2011 05:06:44 GMT

时间到了2011 年 6 月 15 日星期三 05:06:44 GMT

回答by Nitin

To convert the unix time stamp that you are getting to a normal date use this snippet of code:

要将您获得的 unix 时间戳转换为正常日期,请使用以下代码片段:

//date here should be a long

//这里的日期应该很长

long date = (cursor.getColumnIndex(SmsReceiver.DATE));

长日期 = (cursor.getColumnIndex(SmsReceiver.DATE));

String standardDate=DateFormat.getDateInstance().format(new Date(date);

String standardDate=DateFormat.getDateInstance().format(new Date(date);

回答by anilthapliyal

You can use like that

你可以这样使用

public static java.util.Date toDate(java.sql.Timestamp timestamp) {
long millisec = timestamp.getTime() + (timestamp.getNanos() / 1000000);
return new Date(millisec);
}