开发者

How can I format this date?

I have a date that has the format:

"yyyy-MM-dd'T'HH:mm:ss'Z'"
开发者_如何学C

I'd like to convert it to something similar to:

"3 minutes ago"

How can I go about doing this?


See this SO question:

  • How can I calculate a time span in Java and format the output?


Ugly, but does the trick.. and yes, a duplicate! :(

public static void main(String[] args) {
    Calendar c = Calendar.getInstance();
    c.set(2010, 10, 20, 22, 37, 12);

    Date start = c.getTime();

    Date end = new Date();


    long diff = (end.getTime() - start.getTime()) / 1000;

    long days    = diff / (60 * 60 * 24);
    long hours   = diff / (60 * 60) - days * 24;
    long minutes = diff / 60 - (hours * 60 + days * 24 * 60);
    long seconds = diff % 60;

    String output = "";
    if (days >= 1) 
        output += days + " day" + ((days > 1) ? "s" : "");

    if (hours >= 1) 
        output += " " + hours + " hour" + ((hours > 1) ? "s" : "");

    if (minutes >= 1) 
        output += " " + minutes + " minute" + ((minutes > 1) ? "s" : "");

    if (seconds >= 1) 
        output += " " + seconds + " second" + ((seconds > 1) ? "s" : "");

    output = output.trim();

    System.out.println(output);
}


For oarsing the date, check How to parse a date? For displaying it in a nicer format, check for PrettyTime.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜