Mike
Mike

Reputation: 6839

Javascript and mySQL dateTime stamp difference

I have a mySQL database in which I store the time in this format automatically:

2015-08-17 21:31:06

I am able to retrieve this time stamp from my database and bring it into javascript. I want to then get the current date time in javascript and determine how many days are between the current date time and the date time I pulled from the database.

I found this function when researching how to get the current date time in javascript:

Date();

But it seems to return the date in this format:

Tue Aug 18 2015 10:49:06 GMT-0700 (Pacific Daylight Time)

There has to be an easier way of doing this other than going character by character and picking it out from both?

Upvotes: 1

Views: 838

Answers (4)

Jared Smith
Jared Smith

Reputation: 21926

Since none of the other answer got it quite right:

var pieces = "2015-08-17 21:31:06".split(' ');
var date = pieces[0].split('-');
var time = pieces[1].split(':');

var yr = date[0], mon = date[1], day = date[2];
var hour = time[0], min = time[1], sec = time[2];
var dateObj = new Date(yr, mon, day, hr, min, sec);

//if you want the fractional part, omit the call to Math.floor()
var diff = Math.floor((Date.now() - dateObj.getTime()) / (1000 * 60 * 60 * 24));

Note that none of this deals with the timezone difference between the browser and whatever you have stored in the DB. Here's an offset example:

var tzOff = new Date().getTimezoneOffset() * 60 * 1000; //in ms

Upvotes: 0

Souvik Mitra
Souvik Mitra

Reputation: 1

the Date object has a function called getTime(), which will give you the current timestamp in milliseconds. You can then get the diff and convert to days by dividing by (1000 * 3600 * 24) e.g.

var date1 = new Date()
var date2 = new Date()
var diffInMs = date2.getTime() - date1.getTime()
var diffInDays = diffInMs/(1000*3600*24)

Upvotes: 0

Mihai Vilcu
Mihai Vilcu

Reputation: 1967

You can build a new date in javascript by passing the data you receive from your backend as the first argument.
You have to make sure that the format is an accepted one. In your case we need to replace the space with a T. You may also be able to change the format from the back end. Some good examples are available in the MDN docs.

var d = new Date("2015-08-17T21:31:06");
console.log(d.getMonth());

To calculate the difference in days you could do something like this:

var now = new Date();
var then = new Date("2015-08-15T21:31:06");
console.log((now - then)/1000/60/60/24);

Upvotes: 2

Benvorth
Benvorth

Reputation: 7722

You can select the difference directly in your query:

SELECT DATEDIFF(now(), myDateCol) FROM myTable;

Upvotes: 1

Related Questions