Search code examples
javascriptdatetimedate-arithmetic

Storing/Calculating date/time with JS


What is the best practice for saving some time informations in JS?

In my case I want to save the datetime as a user account is created. 36h after creating the account I want to show a message to the user.

Right now I'm saving a timestamp with new Date().getTime();. But maybe it is possible to calculate for some events just with new Date()?

This is how I do it, but it feels not very elegant - especially for complex calculations.

var currentTime = new Date().getTime();
if ( (timeRegistrated + 1000 * 60 * 60 * 36 - currentTime) >= 0 ) {
    console.log('36h are over...');
}

I think I have to use some library for complex calculations (like current age of user or how many months between two dates)... But still the basic question: Which type of date-data should be used for the DB?


Solution

  • Moment.js has a fromNow function. It's way easier.

    http://momentjs.com/

    moment("20111031", "YYYYMMDD").fromNow();