JavaScript: Days Ago from String

Using JavaScript, I would like to return "Today" if the date of a string matches.  

I would like to return "Yesterday" if the date of a string is 1 day old. I would like to return "Two Days Ago" if the date of a string is 2 days old. I would like to return "Three Days Ago" if the date of a string is 3 days old.  Otherwise, I would like the date to be formatted.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">

function formatDateTime(strDate,strCurrent) {
     var dS = new Date(strDate);
     var dC = new Date(strCurrent);

     if (dS.getDate() +'|'+ dS.getMonth() +'|'+ dS.getFullYear()==dC.getDate() +'|'+ dC.getMonth() +'|'+ dC.getFullYear()) return 'Today';
     return ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","December"][dS.getMonth(dS)] + " " + dS.getDate() + ", " + dS.getFullYear();
}

alert( formatDateTime('9/2/2013 1:00:07 AM',  '9/2/2013 3:00:07 PM' )); // Today
alert( formatDateTime('9/1/2013 11:00:07 PM', '9/2/2013 3:00:07 PM' )); // Yesterday
alert( formatDateTime('8/31/2013 11:00:07 PM', '9/2/2013 3:00:07 PM' )); // Two Days Ago
alert( formatDateTime('8/30/2013 11:00:07 PM', '9/2/2013 3:00:07 PM' )); // Three Days Ago
alert( formatDateTime('8/29/2013 11:00:07 PM', '9/2/2013 3:00:07 PM' )); // Aug 29, 2013

</script>
</head>
<body>
</body>
</html>

Open in new window

LVL 16
hankknightAsked:
Who is Participating?
 
leakim971PluritechnicianCommented:
Test page : http://jsfiddle.net/rNUsr/
function resetTime(d) {
    d = new Date(d);
    d.setHours(0);
    d.setMinutes(0);
    d.setSeconds(0);
    d.setMilliseconds(0);
    return d;
}


function formatDateTime(strDate,strCurrent) {
    var dS = resetTime(strDate);
    var dC = resetTime(strCurrent);
    var dt = (dC-dS)/(24*3600*1000); 
    var arr = ["Today", "Yesterday", "Two Days Ago", "Three Days Ago"];
    
    return (dt>=0&&dt<4)?arr[dt]:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","December"][dS.getMonth(dS)] + " " + dS.getDate() + ", " + dS.getFullYear();
}

alert( formatDateTime('9/2/2013 1:00:07 AM',  '9/2/2013 3:00:07 PM' )); // Today
alert( formatDateTime('9/1/2013 11:00:07 PM', '9/2/2013 3:00:07 PM' )); // Yesterday
alert( formatDateTime('8/31/2013 11:00:07 PM', '9/2/2013 3:00:07 PM' )); // Two Days Ago
alert( formatDateTime('8/30/2013 11:00:07 PM', '9/2/2013 3:00:07 PM' )); // Three Days Ago
alert( formatDateTime('8/29/2013 11:00:07 PM', '9/2/2013 3:00:07 PM' )); // Aug 29, 2013

Open in new window

0
 
hankknightAuthor Commented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.