简体   繁体   中英

How to subtract two dates in javascript?

I want to get the difference between tow dates in javascript but my problem is that the first date is the currenet date of the PC :

today = new Date();

and the other date is a text format date like this for example:

other_date = '15.11.2013';

I want the today date to be same format as other_date and then subtract them , How can I change the format of the today to make the same as other_date ? and How I can make them both as date format to subtract them and get the difference correctly???

I would simply use the split function to get the date parts of the date string:

var today = new Date();
var other_date = '15.11.2013';
var dateparts = other_date.split('.');
var otherDate = new Date(dateparts[2], dateparts[1]-1, dateparts[0]); // substract 1 month because month starting with 0

var difference = today.getTime() - otherDate.getTime(); // difference in ms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM