Add two dates times together in javascript - 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?

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)

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

Related

How to set time with AM PM in Javascript Date Object

Say that I have DateTime in this format Fri Feb 02 2018 00:00:00 GMT+0530 (IST)
And from the time picker plugin getting the time 1:10am or 2:30pm in this format.
I am not sure how to calculate and combine/add them both to produce this result:
Fri Feb 02 2018 01:10:00 GMT+0530 (IST) or Fri Feb 02 2018 14:30:00 GMT+0530 (IST)
I wish if there was something to do as simple as this:
new Date(dateString).setHours(1:10am)
Seems like you need to parse it on your own:
function parseDaytime(time) {
let [hours, minutes] = time.substr(0, time.length -2).split(":").map(Number);
if (time.includes("pm") && hours !== 12) hours += 12;
return 1000/*ms*/ * 60/*s*/ * (hours * 60 + minutes);
}
To add it to a date:
new Date(
+new Date("Fri Feb 02 2018 00:00:00 GMT+0530")
+parseDaytime("1:20pm")
);
Here is a simple function to do what your after.
It basically splits the time using a regex, and then calls setHours & setMins, adding 12 hours if pm is selected.
The example below takes the current datetime, and sets 1:10am & 2:40pm..
function setHours(dt, h) {
var s = /(\d+):(\d+)(.+)/.exec(h);
dt.setHours(s[3] === "pm" ?
12 + parseInt(s[1], 10) :
parseInt(s[1], 10));
dt.setMinutes(parseInt(s[2],10));
}
var d = new Date();
console.log(d);
setHours(d, "1:10am");
console.log(d);
setHours(d, "2:40pm");
console.log(d);
You can parse the time string into hours & minutes, adjust the hours according to am/pm & set it to the date object then:
var dateString = 'Fri Feb 02 2018 00:00:00 GMT+0530 (IST)';
var hoursString = '2:30pm';
var parts = hoursString.replace(/am|pm/, '').split(':')
var hours = parseInt(parts[0]) + (hoursString.indexOf('pm') !== -1 ? 12 : 0);
var minutes = parts[1];
var date = new Date(dateString);
date.setUTCHours(hours, minutes);
console.log(date); // in your local time
console.log(date.toUTCString()); // in UTC (i.e. without timezone offset)
(Note setHours / setUTCHours mutates date object but returns unix timestamp of the updated datetime.)

Incorrect Javascript Day When Added?

I have a javascript function that takes in a number X and a date, and returns a new Date that is X number of days away:
function addDays(theDate, numDaysToAdd) {
var newDate = new Date();
return new Date(newDate.setDate(theDate.getDate() + numDaysToAdd));
}
I pass it a day that is Sat Jul 02 2016 16:03:06 GMT-0700 (Pacific Daylight Time) and a number 7, but the result I got was Thu Jun 09 2016 16:05:32 GMT-0700 (Pacific Daylight Time). Why is it giving me the correct date but wrong month?
The problem is that newDate is always created from the current date (new Date()). In other words, if this function is executed in June it will produce a date in June, then try to set a the day of the month as a offset from the input date.
You need to construct newDate as a copy of theDate:
function addDays(theDate, numDaysToAdd) {
var newDate = new Date(theDate);
newDate.setDate(theDate.getDate() + numDaysToAdd);
return newDate;
}
var d = new Date('Sat Jul 02 2016 16:03:06 GMT-0700 (Pacific Daylight Time)');
console.log(addDays(d, 7).toString());
You can add number of milliseconds to given date and it will generate correct date.
getTime() returns milliseconds from epoch.
offset = numDaysToAdd * 24 * 60 * 60 * 1000;
24: Hours in a day
60: Minutes in an hour
60: seconds in a minute
1000: milliseconds in a second
Date constructor takes milliseconds from epoch
function addDays(theDate, numDaysToAdd) {
var start = theDate.getTime();
var offset = numDaysToAdd * 24 * 60 * 60 * 1000;
return new Date(start + offset);
}
var today = new Date();
console.log(today, addDays(today, 10));

sethours updating time part but not the date part in date time field

I've a datetime field with date only as format. Also, I've added a script at onload so that whenever a record is accessed 12:00 should be added to that field. It works as expected and add 12 hours to the time part. But it do not update the date accordingly.
For example, I've Date Become Manager field and its value is 'Thu Apr 30 23:00:00 UTC-1200 1992'. And after adding 12 hours it updates the time part as 'Thu Apr 30 12:00:00 UTC-1200 1992' but do not add anything to its date. Following is my snippet for this to update.
function updateFields(field){
var dateField = Xrm.Page.getAttribute(field);
if(dateField.getValue()== null)
{
dateField.setValue(new Date());
}
dateField.setValue(dateField.getValue().setHours(12, 0, 0));
}
Please let me know if I am doing something wrong in it.
setHours only changes the time, it doesn't compute anything.
The most common way to perform this kind of computation is this:
var numberOfHours = 12; // how many hours you want to add. Can be *negative* too.
var millisecondsInAnHour = 60 * 60 * 1000; // this is constant
var offset = numberOfHours * millisecondsInAnHour;
var newFieldValue = dateField.getValue().getTime() + offset;
dateField.setValue(newFieldValue);
Basically, you grab the time of the value and add/subtract a number of milliseconds to it.
So to be clear, you want to add 12 hours to the current date value, (as opposed to just setting time element to 12:00)?
setHours just sets the time, it doesn't add 12 hours to the time. If you do it multiple times it will always be 12 hours, rather than 0 - 12 - 24.
If you combine setHours with getHours you should be able to achieve the desired behaviour.
var d1 = new Date();
console.log("Original Date: " + d1);
d1.setHours(12);
console.log("Set 12 Hours Once: " + d1);
d1.setHours(12);
console.log("Set 12 Hours Twice: " + d1);
var d2 = new Date();
console.log("Original Date 2: " + d2);
d2.setHours(d2.getHours() + 12);
console.log("Add 12 Hours Once: " + d2);
d2.setHours(d2.getHours() + 12);
console.log("Add 12 Hours Twice: " + d2);
Output:
Original Date: Tue Sep 22 2015 09:45:39 GMT+0100 (GMT Daylight Time)
Set 12 Hours Once: Tue Sep 22 2015 12:45:39 GMT+0100 (GMT Daylight Time)
Set 12 Hours Twice: Tue Sep 22 2015 12:45:39 GMT+0100 (GMT Daylight Time)
Original Date 2: Tue Sep 22 2015 09:45:39 GMT+0100 (GMT Daylight Time)
Add 12 Hours Once: Tue Sep 22 2015 21:45:39 GMT+0100 (GMT Daylight Time)
Add 12 Hours Twice: Wed Sep 23 2015 09:45:39 GMT+0100 (GMT Daylight Time)
I just updated my code and it works. Please have a look into following code snippet.
function updateFields(field){
var dateField = Xrm.Page.getAttribute(field);
if(dateField.getValue()== null)
{
dateField.setValue(new Date());
}
dateField.setValue(dateField.getValue().setHours(dateField.getValue().getHours() + 12));}

How to set Hours,minutes,seconds to Date which is in GMT

I have Date Object ,I wanted to clear HOUR,MINUTE and SECONDS from My Date.Please help me how to do it in Javascript. Am i doing wrong ?
var date = Date("Fri, 26 Sep 2014 18:30:00 GMT");
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
Expected result is
Fri, 26 Sep 2014 00:00:00 GMT
How Do I achieve ?
According to MDN the setHours function actually takes additional optional parameters to set both minutes, seconds and milliseconds. Hence we may simply write
// dateString is for example "Fri, 26 Sep 2014 18:30:00 GMT"
function getFormattedDate(dateString) {
var date = new Date(dateString);
date.setHours(0, 0, 0); // Set hours, minutes and seconds
return date.toString();
}
You can use this:
// Like Fri, 26 Sep 2014 18:30:00 GMT
var today = new Date();
var myToday = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
Recreate the Date object with constructor using the actual date.
To parse the date into JavaScript simply use
var date = new Date("Fri, 26 Sep 2014 18:30:00 GMT”);
And then set Hours, Minutes and seconds to 0 with the following lines
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.toString() now returns your desired date

How to compare the date part alone from a date time value

I have two variables namely
date1 = Mon Nov 25 2013 00:00:00 GMT+0530 (IST)
date2 = Mon Nov 25 2013 14:13:55 GMT+0530 (IST)
When I compare the two dates I get that date2 is greater which I need is correct. But I do not want to check the time part of the two dates I have. How could I get the date part alone from these two dates and compare it?
var today = new Date(); //Mon Nov 25 2013 14:13:55 GMT+0530 (IST)
d = new Date(my_value); //Mon Nov 25 2013 00:00:00 GMT+0530 (IST)
if(d>=today){ //I need to check the date parts alone.
alert(d is greater than or equal to current date);
}
Try clearing the time using Date.setHours:
dateObj.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])
Example Code:
var today = new Date();
today.setHours(0, 0, 0, 0);
d = new Date(my_value);
d.setHours(0, 0, 0, 0);
if(d >= today){
alert(d is greater than or equal to current date);
}
The best way would be to modify the accepted answer's if statement as follows
if(d.setHours(0,0,0,0) >= today.setHours(0,0,0,0))
In this way, you can easily check for equality as well because the return type for setHours() is integer.
Try:
var today = new Date(); //Mon Nov 25 2013 14:13:55 GMT+0530 (IST)
var d = new Date(my_value); //Mon Nov 25 2013 00:00:00 GMT+0530 (IST)
var todayDateOnly = new Date(today.getFullYear(),today.getMonth(),today.getDate()); //This will write a Date with time set to 00:00:00 so you kind of have date only
var dDateOnly = new Date(d.getFullYear(),d.getMonth(),d.getDate());
if(dDateOnly>=todayDateOnly){
alert(d is greater than or equal to current date);
}
var StartDate = $("#StartDate").val();
var EndDate = $("#EndDate").val();
if ((( EndDate - StartDate)/ (86400000*7))<0)
{
alert("Start Date Must Be Earlier Than End Date"); $("#StartDate").focus();
error = true;
return false;
}

Categories