开发者

format ISO date/time and later compare to phone's date/time

I've got a String of a date/time in ISO-8601 format, like: 2011-04-15T20:08:18Z

I want to format this to a more readable date/time and then also be able to compare that later to the phone's local time. I'm a bit confused about what's been deprecated and what hasn't. Do I need to use a Calendar object?

Can someone walk me through 开发者_运维知识库how to do this?


following is a code snippet you can use

StringBuffer sbDate = new StringBuffer();
sbDate.append(cDate);
String newDate = sbDate.substring(0, 19).toString();
String rDate = newDate.replace("T", " ");
String nDate = rDate.replaceAll("-", "/");

nDate will give you date in normal format, to compare two dates continue like

long epoch = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(nDate).getTime();
Date currentDate = new Date();
long diffInSeconds = (currentDate.getTime() - epoch) / 1000;
String elapsed = "";
long seconds = diffInSeconds;
long mins = diffInSeconds / 60;
long hours = diffInSeconds / 3600;
long days = diffInSeconds / 86400;
long weeks = diffInSeconds / 604800;
long months = diffInSeconds / 2592000;

if (seconds < 120) {
    elapsed = "a min ago";
} else if (mins < 60) {
    elapsed = mins + " mins ago";
} else if (hours < 24) {
    elapsed = hours + " "+ (hours > 1 ? "hrs" : "hr")+ " ago";
} else if (hours < 48) {
    elapsed = "a day ago";
} else if (days < 7) {
    elapsed = days + " days ago";
} else if (weeks < 5) {
    elapsed = weeks + " " + (weeks > 1 ? "weeks" : "week") + " ago";
} else if (months < 12) {
    elapsed = months" " + (months > 1 ? "months" : "months")+ " ago";
} else {
    elapsed = "more than a year ago";
}

This way you'll be able to get date in proper format as well as you'll be able to compare the dates and get the difference in Years, months, weeks, days, hours, mins or secs.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜