开发者

convert timestamp to date

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.

int date      = (cursor.getColumn开发者_运维知识库Index(SmsReceiver.DATE));

this returns some number like 1308114404722.

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


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

To format a Date object, use for example 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 int is not large enough. (In fact, the number 1308114404722 doesn't even fit in a 32-bit int).



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


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


Try:

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


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

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

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


You can easily convert the timestamp. I've multiplied by 1000 because some people usually divide by 1000 when saving the timestamp. You can try with the 1000 or without.

    DateFormat format = new SimpleDateFormat("h:mm a");
    Date date = new Date();
    date.setTime(Long.parseLong(YOUR_INT_OR_LONG_TIMESTAMP)*1000);
    String readableTime = format.format(date);

You can explore more formatting options in the documentation


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

//date here should be a long

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜