For the last few days I was struggling with iterating through a range of dates. I was using following piece of code to test:
var current_date = new Date("2014-08-01");
var end_date = new Date("2014-10-31");
var end_date_time = end_date.getTime();
while (current_date.getTime() <= end_date_time) {
document.write(current_date + '<br>');
current_date.setDate(current_date.getDate()+1);
}
To me it looks correct, but there's a problem. It's missing the last day. I was turning this code around, used a for- loop, defined new Date within loop and all the things you can imagine. One thing stayed the same. Last day missing!
By curiosity I used following format to create the Dates:
var current_date = new Date("08/01/2014");
var end_date = new Date("10/31/2014");
And to my surprise, it worked as expected. Now I'm wondering if this is a normal behaviour or a bug in Date?
I would be thankfull, if someone can enlighten me.
that is because there was a change in time, check that the first days are in GMT Daylight Time and the lasts in (GMT Standard Time)
so your code better to use UTC
var current_date = new Date("2014-08-01");
current_date = new Date(current_date.getUTCFullYear(), current_date.getUTCMonth(), current_date.getUTCDate(), current_date.getUTCHours(), current_date.getUTCMinutes(), current_date.getUTCSeconds());
var end_date = new Date("2014-10-31");
end_date = new Date(end_date.getUTCFullYear(), end_date.getUTCMonth(), end_date.getUTCDate(), end_date.getUTCHours(), end_date.getUTCMinutes(), end_date.getUTCSeconds());
var end_date_time = end_date.getTime();
while (current_date <= end_date) {
document.write(current_date + '<br>');
current_date.setDate(current_date.getDate()+1);
}
Related
Trying out a Jquery to confirm if date selected is equal to today or greater than.
If i select today, it return it as the day selected is less than today. Selecting previous day works well but selecting today returns less than. Any tip.
var firstRepaymentDate = new Date($('#First_Repayment_Date').val());
var today = new Date();
if (firstRepaymentDate.getTime() < today.getTime()) {
alert('The First Repayment Date Can only Be Today Or Future Date');
return false;
}
Don't forget that new Date() will include the current time as well. You'll need to remove that time component with today.setHours(0,0,0,0) for the comparison to be correct.
Also, setHours() returns the underlying value like getTime() so you can do
var firstRepaymentDate = new Date($('#First_Repayment_Date').val());
var today = new Date();
if (firstRepaymentDate.getTime() < today.setHours(0,0,0,0)) {
alert('The First Repayment Date Can only Be Today Or Future Date');
return false;
}
In response to the comment about adding 20 days:
This is a little more detailed but is fairly easy.
var today = new Date();
var plus20Days = new Date(today.setDate(today.getDate() + 20));
again you can then use setHours() to reset the time component.
new Date() considers time too, not only the date. I think the easiest way to achieve this is to compare years, months and days by using respectively getFullYear() , getMonth() , getDate().
Check all the methods that manipulate js Date here
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Date
I'm trying to increment one day to a given date. My code, inspired by this answer, looks like:
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(date.getDate() + 1);
However, I'm seeing a strange behaviour. Today is December 5th, 2019. If the user selects January 1, 2020 (stored in date variable), then backupDate ends up being January 2nd, 2019, instead of 2020. What is wrong with this code? How should I go about incrementing the date, if what I'm doing is wrong?
Note: because of whatever policies my company has, I can't use any JavaScript library other than jQuery.
new Date() returns the current Date(example: 05/12/2019). You are just changing the date alone in current date. Still the year is 2019.
it should be like,
date.setDate(date.getDate() + 1);
if you can't change the original date object, then it can be done like this,
var changedDate = new Date(date);
changedDate.setDate(changedDate.getDate() + 1);
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(new Date(date).getDate() + 1);
nextDay is one day after date:
var date = getDateFromUIControl();
var nextDay = new Date(date.getYear(), date.getMonth(), date.getDate()+1);
Also you don't need to worry about overflowing d.getDate()+1 (e.g. 31+1) - the Date constructor is smart enough to go into the next month.
I am using a function in Angular JS to generate the dates for the past one week starting from today's date. I am storing these dates in an array and then using that array to flood a dropdown.
The following is the code that is being used by me.
generate() {
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Here convert is a function which is being used to convert the dates to the required format. A screenshot of generated dates is attached below.
As evident from the screenshot, the last two dates are incorrect. Can somebody explain to me, what the problem is?
The setDate() method sets the day of the Date object relative to the
beginning of the currently set month.
The above is from MDN.
Your code works for the first 5 dates, but once you are modifying your February date with -1, it sets the day relative to the current month e.g. February. So this will turn into January (as you are setting the day to -1), same happens in the next iteration and you get December.
For an easy fix you can just set the date variable to new Date() in the first line of your for loop.
The issue here is using the same date variable in the loop. You need to re-initialize it.
As can be seen in Parameters Value section in the link here. Zero and negative values in setDate() sets the date from previous month.
Hence at setDate(0), date value is set to last day of Feb. Now since you are using the same variable, setDate(-1) takes the previous month from Feb hence you get Jan.
You need to change the code to something like this:
generate() {
this.date_new = [];
var date1 = new Date();
for (var i = 0; i < 7; i++) {
// re-initialize date
var date = new Date();
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Hope this helps :)
The issue here is that negative numbers inside the setDate method don't work quite well.
Please update the code to something like below:
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date= new Date(date1.getFullYear(), date1.getMonth(),date1.getDate()-i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
Hope this will solve your problem.
I m trying to do the following :
Storing Current day +1 (Tomorrow's date) ( CurrentDay is the StartDay,wrong naming alias,my bad)
calculating 7 days from date from 1st Step
Everyday checking presentDay, and if is equal to 7th day, run my logic.
Problem I m facing is :
The DateObject I store is in a numerical format and it also saves the time. I want only the date for comparison.
Is it possible to directly compare dates? I do not really wish to use 3rd party library.
Any help will be appreciated.
Code :
var d = new Date();
var stdate = d.setDate(d.getDate() + 1); //output something like 1526407850028 ( last few digits changes every second)
var weeklyDate = new Date();
var wkdate = weeklyDate.setDate(weeklyDate.getDate() + 7); //output Ex : 1526926307437
var presentDay = new Date();
var pdate = presentDay.setDate(presentDay.getDate());
if (pdate == wkdate) { // I want only date comparison
// my logic
}
Try keeping your steps more separate. For instance, why not just compare the date values by calling Date.prototype.getDay()? Then you're not working with all of that other stuff. You can also reduce the number of calls to new Date(), so the whole thing would be:
//calculate target date
let d = new Date(); // returns an integer between 0-6
var stDay = (d.getDay()+1)%7; //tomorrow's day of week kept between 0-6 by modulus
//daily check runs in separate function
let today = new Date();
if( today.getDay() === stDay){
//logic
}
developer.mozilla.org - Date.prototype.getDay()
I am trying to create a simple script that gives me the next recycling date based on a biweekly schedule starting on Wed Jul 6, 2011. So I've created this simple function...
function getNextDate(startDate) {
if (today <= startDate) {
return startDate;
}
// calculate the day since the start date.
var totalDays = Math.ceil((today.getTime()-startDate.getTime())/(one_day));
// check to see if this day falls on a recycle day
var bumpDays = totalDays%14; // mod 14 -- pickup up every 14 days...
// pickup is today
if (bumpDays == 0) {
return today;
}
// return the closest day which is in 14 days, less the # of days since the last
// pick up..
var ms = today.getTime() + ((14- bumpDays) * one_day);
return new Date(ms);
}
and can call it like...
var today=new Date();
var one_day=1000*60*60*24; // one day in milliseconds
var nextDate = getNextDate(new Date(2011,06,06));
so far so good... but when I project "today" to 10/27/2011, I get Tuesday 11/8/2011 as the next date instead of Wednesday 11/9/2011... In fact every day from now thru 10/26/2011 projects the correct pick-up... and every date from 10/27/2011 thru 2/28/2012 projects the Tuesday and not the Wednesday. And then every date from 2/29/2012 (leap year) thru 10/24/2012 (hmmm October again) projects the Wednesday correctly. What am I missing? Any help would be greatly appreciated..
V
The easiest way to do this is update the Date object using setDate. As the comments for this answer indicate this isn't officially part of the spec, but it is supported on all major browsers.
You should NEVER update a different Date object than the one you did the original getDate call on.
Sample implementation:
var incrementDate = function (date, amount) {
var tmpDate = new Date(date);
tmpDate.setDate(tmpDate.getDate() + amount)
return tmpDate;
};
If you're trying to increment a date, please use this function. It will accept both positive and negative values. It also guarantees that the used date objects isn't changed. This should prevent any error which can occur if you don't expect the update to change the value of the object.
Incorrect usage:
var startDate = new Date('2013-11-01T11:00:00');
var a = new Date();
a.setDate(startDate.getDate() + 14)
This will update the "date" value for startDate with 14 days based on the value of a. Because the value of a is not the same is the previously defined startDate it's possible to get a wrong value.
Expanding on Exellian's answer, if you want to calculate any period in the future (in my case, for the next pay date), you can do a simple loop:
var today = new Date();
var basePayDate = new Date(2012, 9, 23, 0, 0, 0, 0);
while (basePayDate < today) {
basePayDate.setDate(basePayDate.getDate()+14);
}
var nextPayDate = new Date(basePayDate.getTime());
basePayDate.setDate(nextPayDate.getDate()-14);
document.writeln("<p>Previous pay Date: " + basePayDate.toString());
document.writeln("<p>Current Date: " + today.toString());
document.writeln("<p>Next pay Date: " + nextPayDate.toString());
This won't hit odd problems, assuming the core date services work as expected. I have to admit, I didn't test it out to many years into the future...
Note: I had a similar issue; I wanted to create an array of dates on a weekly basis, ie., start date 10/23/2011 and go for 12 weeks. My code was more or less this:
var myDate = new Date(Date.parse(document.eventForm.startDate.value));
var toDate = new Date(myDate);
var week = 60 * 60 * 24 * 7 * 1000;
var milliseconds = toDate.getTime();
dateArray[0] = myDate.format('m/d/Y');
for (var count = 1; count < numberOccurrences; count++) {
milliseconds += week;
toDate.setTime(milliseconds);
dateArray[count] = toDate.format('m/d/Y');
}
Because I didn't specify the time and I live in the US, my default time was midnight, so when I crossed the daylight savings time border, I moved into the previous day. Yuck. I resolved it by setting my time of day to noon before I did my week calculation.