Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two dates times together in javascript

I am trying to add two dates:

date start Fri Apr 26 2013 16:08:03 GMT+0100 (Paris, Madrid)
+  
date periode Fri Apr 26 2013 00:10:00 GMT+0100 (Paris, Madrid)

I used this code:

var periode=$("#dure").val();
var start = $("#start").val()
var end =$("#end").val();

var dateStart= new Date(start);
console.log('start');
console.log(dateStart);

var date=dateStart.format('yyyy-mm-dd'); 
per=date+' '+periode;
var datePeriode= new Date(per);

console.log('datePeriode');
console.log(datePeriode);
var dateEnd= dateStart.getTime()+datePeriode.getTime();
console.log('dateEnd');
console.log(dateEnd);

In my JavaScript console, I get:

dateDebut
Fri Apr 26 2013 16:33:11 GMT+0100 (Paris, Madrid)
datePeriode
Fri Apr 26 2013 00:15:00 GMT+0100 (Paris, Madrid)
dateEnd
2733922091000

How can I fix that? Am I missing something?

like image 876
Takwa Chammam Avatar asked Apr 26 '13 15:04

Takwa Chammam


2 Answers

If you want to add a time period to a date, you basically have to convert both of them into milliseconds.

var date = new Date();
var dateMillis = date.getTime();

//JavaScript doesn't have a "time period" object, so I'm assuming you get it as a string
var timePeriod = "00:15:00"; //I assume this is 15 minutes, so the format is HH:MM:SS

var parts = timePeriod.split(/:/);
var timePeriodMillis = (parseInt(parts[0], 10) * 60 * 60 * 1000) +
                       (parseInt(parts[1], 10) * 60 * 1000) + 
                       (parseInt(parts[2], 10) * 1000);

var newDate = new Date();
newDate.setTime(dateMillis + timePeriodMillis);

console.log(date); //eg: Fri Apr 26 2013 08:52:50 GMT-0700 (MST)
console.log(newDate); //eg: Fri Apr 26 2013 09:07:50 GMT-0700 (MST)
like image 182
Vivin Paliath Avatar answered Oct 02 '22 20:10

Vivin Paliath


Convert datePeriod to milliseconds instead of making it into a date object for your addition.

You need to convert the sum to a date. getTime() is in milliseconds since 1-1-1970. So you want to do.

var ending = new Date();
ending.setTime(dateEnd);
console.log(ending);

setTime will set the date properly for you.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setTime

like image 39
Schleis Avatar answered Oct 02 '22 21:10

Schleis