Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to determine date and output either "time" if it is today, "yesterday" for yesterday, and the actual date if it is before then

I am creating an simple email client and I want the inbox to display the date that the email was received in the format:

Today at 13:17

Yesterday at 20:38

13 January at 17:15

21 December 2012 @ 18:12

I am retrieving the data from a database, outputting it to xml (so everything can be done through AJAX) and printing the results to a <ul><li> format.

The Date and Time are stored separately in the format:

Date(y-m-d)

Time(H:i:s)

what i have so far

I see that something like that is possible with php. Here - PHP: date "Yesterday", "Today"

Is this possible using javascript?

like image 608
Michael Avatar asked Jan 15 '13 13:01

Michael


1 Answers

I would go about with something like this

function getDisplayDate(year, month, day) {
    today = new Date();
    today.setHours(0);
    today.setMinutes(0);
    today.setSeconds(0);
    today.setMilliseconds(0);
    compDate = new Date(year,month-1,day); // month - 1 because January == 0
    diff = today.getTime() - compDate.getTime(); // get the difference between today(at 00:00:00) and the date
    if (compDate.getTime() == today.getTime()) {
        return "Today";
    } else if (diff <= (24 * 60 * 60 *1000)) {
        return "Yesterday";
    } else { 
        return compDate.toDateString(); // or format it what ever way you want
    }
}

than you should be able to get the date like this:

getDisplayDate(2013,01,14);
like image 160
xblitz Avatar answered Oct 15 '22 05:10

xblitz