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));
Related
I have issue with a date.
I have two date (start and end) and I need to build an array of all date between these two.
My script is something like:
while(currentData < nodeLastDate){
currentData.setDate(currentData.getDate() + 1);
console.log(currentData)
}
But at Sat Mar 30 2019 there is an error and the data change also the time.
if you run this simple script you can see it.
let test = new Date(2019, 2, 30, 2)
console.log(test)
test = test.setDate(test.getDate() + 1)
console.log(new Date(test))
this is the result:
Sat Mar 30 2019 02:00:00 GMT+0100 (Ora standard dell’Europa centrale)
index.js?c69d:385 Sun Mar 31 2019 03:00:00 GMT+0200 (Ora legale dell’Europa central)
Is this normal?
Date.getDate() gets the day of the month, so you lose any other information. If you want to add a day to a date, simply use Date.getTime() and add the number of milliseconds in a day:
let test = new Date(2019, 2, 30, 2)
console.log(test)
test = test.setDate(test.getTime() + (1440 * 60000))
console.log(new Date(test))
Date.getTime returns the number of milliseconds since an arbitrary date known as the epoch date, so adding the number of milliseconds in a day will add exactly one day to your date. (1440 * 60000 is the number of milliseconds in a day because there are 1440 minutes in a day and 60000 milliseconds in a minute)
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.)
I have this code to calculate, based on the user's computer's time, the milliseconds until Midnight CST.
For the timezone I am in, now.getTimezoneOffset() returns 420, making tmzOfst 60.
function millisToMidnight() {
var now = new Date();
var tmzOfst = (now.getTimezoneOffset())-360; //-360 minutes = CST
now.setHours(-(tmzOfst/60));// Adjust 'now' to CST time
var then = new Date(now); //make a var same as now
then.setHours(24, 0, 0, 0); //set to midnight
return (then - now); //calculate difference
}
However, when I run this (console.log's everywhere), I get this:
Now = Tue Mar 07 2017 21:51:05 GMT-0700 (Mountain Standard Time)
tmzOfst = 120
Then = Mon Mar 06 2017 22:51:05 GMT-0700 (Mountain Standard Time)
Which, as you can see, correctly changes the time to CST, however, it ends up changing the date one day as well. Is there a easier way to do this? Why does it change the day?
if you want to ADJUST the hours, you need to adjust, not SET
now.setHours(now.getHours()-(tmzOfst/60));
This should give you the milliseconds for the coming midnight.
function millisToMidnight() {
var date = new Date();
date.setDate(date.getDate() + 1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
return date.getTime() - (new Date()).getTime();
}
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
I have lead_creat_date and I need to compare it against 20 days before date ( let's say today is aug-4-2011, than I need july-14-2011). So comparison against lead_creat_date and July-14-2011.
if ( lead_creat_date > july-14-2011)
{
alert('lead_creat_date is greater');
}
How can I do this comparison in JavaScript?
I'm trying using the JavaScript date object. I did get one number for 20 days before date, using setDate() & getDate() function but I don't know how to convert lead_creat_date into a JavaScript date() object.
Thanks.
It's likely you can use the Date.parse() method.
It really depends on your date format.
I'll assume lead_creat_date is a Date object, seeing as it's not clear...
It depends on how accurate you need to be. You can do something like this, which will go back exactly 20 days, to the millisecond.
var now = new Date().getTime() - 20 * 24 * 60 * 60 * 1000;
if (lead_creat_date > now) {
alert('lead_creat_date is greater');
}
If you only care about the day, you could probably do this
var now = new Date().getTime() - 20 * 24 * 60 * 60 * 1000;
now = new Date(now.toDateString());
if (lead_creat_date > now) {
alert('lead_creat_date is greater');
}
References:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toDateString
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
To convert a string to a date, convert the parts to numbers to use as input to the Date constructor. e.g. if your date is July-14-2011 then you can convert it using:
var dateString = 'July-14-2011';
var months = {january:0, february:1, march:2, april:3,
may:4, june:5, july:6, august:7, september:8,
october:9, november:10, december:11};
var dateBits = dateString.split('-');
var monthNumber = months[dateBits[0].toLowerCase()];
// Date object for date string
var date = new Date(dateBits[2], monthNumber, dateBits[1]);
// 20 days prior
date.setDate(date.getDate() - 20); // 24 Jun 2011
Edit
If your date format is 8/27/2009 10:23:00 AM the you can convert to a date using:
var dateString = '8/3/2011 10:23:00 AM';
var dateBits = dateString.split(/[ \/]/);
var date = new Date(dateBits[2], dateBits[0] - 1, dateBits[1]);
// 20 days prior
date.setDate(date.getDate() - 20); // 14 Jul 2011
alert(date);
If you need to include the time, you can include it using the same strategy, e.g.
var dateString = '8/3/2011 10:23:00 AM';
var dateBits = dateString.split(/[ \/:]/);
if (dateBits[6].toLowerCase() == 'pm') {
dateBits[3] = +dateBits[3] + 12;
}
// Thu 14 Jul 2011 10:23:00
var date = new Date(dateBits[2], dateBits[0] - 1, dateBits[1] - 20,
dateBits[3], dateBits[4], dateBits[5]);
and as a function:
function offsetDate(dateString, offset) {
var dateBits = dateString.split(/[ \/:]/);
if (dateBits[6].toLowerCase() == 'pm') {
dateBits[3] = +dateBits[3] + 12;
}
return new Date(dateBits[2], dateBits[0] - 1,
+dateBits[1] + +offset,
dateBits[3], dateBits[4], dateBits[5]);
}
// Thu 14 Jul 2011 10:23:00
alert(offsetDate('8/3/2011 10:23:00 AM', -20));
// Tue 23 Aug 2011 22:23:00
alert(offsetDate('8/3/2011 10:23:00 PM', +20));
// Wed 18 Jan 2012 10:23:00
alert(offsetDate('12/29/2011 10:23:00 AM', +20));