Search code examples
javascriptpretty-printdate-formatting

Show time of future in pretty format using javascript


Is there a javascript which can work for future? For example i want to post an event dated on 1/11/2012, i need it to show as "one month from now" or something similar in the web page. I have gone through pretty dates but looks like it doesn't work some times. Is there something which works for past and future time?


Solution

  • function func()
    {
        var mEvent = new Date('11/1/2012');
        var now = new Date();
    
        var timeDif = mEvent.getTime() - now.getTime();
        var dSec, dMin, dHr, dDay;
    
        dSec = (timeDif / 1000);
        dMin = (dSec / 60);
        dHr = (dMin / 60);
        dDay = (dHr / 24);
    
        var mStr = (dDay>>0) + "d, " + (dHr>>0) + "h, " + (dMin>>0) + 'm, ' + (dSec>>0) + "s.";
    
        if (now < mEvent)
            alert('future: ' + mStr);
        else
            alert('past: ' + mStr);
    }