31 days in February in Date object - javascript

This code should log all days for given month:
var date = new Date(2012,2,1);
var thisMonth = date.getMonth();
while(date.getMonth()==thisMonth) { // 31 steps ???
console.log(date.getMonth(),date.getDate());
date.setDate(date.getDate()+1);
}
It works well for every month but February. Any ideas where is the catch?

Note the month parameter is 0-indexed, so your code is about March not February.
The doc:
month
Integer value representing the month, beginning with 0 for January to
11 for December.

Use new Date(2012,1,1); month is zero-based ;-)

This is pretty interesting:
new Date('2014-02-28'); // Fri Feb 28 2014 01:00:00 GMT+0100
new Date('2014-02-29'); // Sat Mar 01 2014 01:00:00 GMT+0100
new Date('2014-02-30'); // Sun Mar 02 2014 01:00:00 GMT+0100
new Date('2014-02-31'); // Mon Mar 03 2014 01:00:00 GMT+0100
new Date('2014-02-32'); // Invalid Date

Related

How to increase the date when moving to the other month

I have a date set which I am filling it with the number of current week and year:
dateSets(week, year) {
let fistDayOfTheWeek = '';
if(this.currentWeekNumber === this.getWeekNumber(new Date())) {
fistDayOfTheWeek = new Date();
} else {
fistDayOfTheWeek = this.getDateOfWeek(week, year);
}
let sunday = new Date(fistDayOfTheWeek);
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
const dates = [];
const diff = sunday.getDate() - fistDayOfTheWeek.getDate();
for (let i = 0; i <= diff; i++) {
const upDate = new Date();
upDate.setDate(fistDayOfTheWeek.getDate() + i);
dates.push(upDate);
}
console.log(dates)
return dates;
},
So apperantly my dateSet function works like if it is not monday then show the dates from today to sunday and from next week from monday to sunday. But what is wrong in this function is it doesnt push when the month is changed. So for 4 weeks console.log(dates) displays:
[Tue Aug 10 2021 16:22:43 GMT+0200 (Central European Summer Time),
Wed Aug 11 2021 16:22:43 GMT+0200 (Central European Summer Time), Thu
Aug 12 2021 16:22:43 GMT+0200 (Central European Summer Time), Fri Aug
13 2021 16:22:43 GMT+0200 (Central European Summer Time), Sat Aug 14
2021 16:22:43 GMT+0200 (Central European Summer Time), Sun Aug 15
2021 16:22:43 GMT+0200 (Central European Summer Time)]
[Mon Aug 16 2021 16:22:46 GMT+0200 (Central European Summer Time),
Tue Aug 17 2021 16:22:46 GMT+0200 (Central European Summer Time), Wed
Aug 18 2021 16:22:46 GMT+0200 (Central European Summer Time), Thu Aug
19 2021 16:22:46 GMT+0200 (Central European Summer Time), Fri Aug 20
2021 16:22:46 GMT+0200 (Central European Summer Time), Sat Aug 21
2021 16:22:46 GMT+0200 (Central European Summer Time), Sun Aug 22
2021 16:22:46 GMT+0200 (Central European Summer Time)]
[Mon Aug 23 2021 16:22:47 GMT+0200 (Central European Summer Time),
Tue Aug 24 2021 16:22:47 GMT+0200 (Central European Summer Time), Wed
Aug 25 2021 16:22:47 GMT+0200 (Central European Summer Time), Thu Aug
26 2021 16:22:47 GMT+0200 (Central European Summer Time), Fri Aug 27
2021 16:22:47 GMT+0200 (Central European Summer Time), Sat Aug 28
2021 16:22:47 GMT+0200 (Central European Summer Time), Sun Aug 29
2021 16:22:47 GMT+0200 (Central European Summer Time)]
[]
As you see since after 3 weeks, the month will be changed to september and I think that's why it comes to an empty array.
I dont know if it is necessary but in any case here are the other functions that I used:
getDateOfWeek(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
return ISOweekStart;
}
getWeekNumber(date) {
const temp_date = new Date(date.valueOf());
const dayn = (date.getDay() + 6) % 7;
temp_date.setDate(temp_date.getDate() - dayn + 3);
const firstThursday = temp_date.valueOf();
temp_date.setMonth(0, 1);
if (temp_date.getDay() !== 4)
{
temp_date.setMonth(0, 1 + ((4 - temp_date.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstThursday - temp_date) / 604800000);
},
PS: currentWeekNumber is increasing everytime when the button is clicked.
Your issue is here:
const diff = sunday.getDate() - fistDayOfTheWeek.getDate();
when you get to the end of the month of say August, the next Sunday is 5 Sep and the first day of the week is 30 August, so diff is -25 and in the test:
for (let i = 0; i <= diff; i++) {
i is less than diff from the start so nothing is added to the array.
One fix is to get the number of days until the next Sunday and iterate for that many days, e.g.
// Return an array of dates from tomorrow until the
// following Sunday.
function getDatesToSunday(date = new Date()) {
// Copy date so don't affect original
let d = new Date(+date);
// Get the number of days until the next Sunday
let count = 7 - d.getDay();
// Create array of Dates
let dates = [];
while (count--) { 
dates.push (new Date(d.setDate(d.getDate() + 1)));
}
return dates;
}
console.log('Given Sun 29 Aug 2021:');
getDatesToSunday(new Date(2021, 7, 29))
.forEach(d => console.log(d.toDateString()));
console.log('Rest of this week, or next if today is Sunday:');
getDatesToSunday()
.forEach(d => console.log(d.toDateString()));
If the supplied date is Saturday, the above returns an array of just Sunday. If the supplied date is Sunday, it returns an array of the following Monday to Sunday, etc.
If you want to get multiple weeks of dates, add a second parameter, say weeks that defaults to 1, then add (weeks - 1) * 7 to count before the while loop. Test weeks first to ensure it's 1 or greater (starting a decrementing while loop with a negative number is not a good idea).
Or you can just keep adding days until Sunday:
const getDatesToSunday = (date = new Date()) => {
// Setup
let year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
dates = [];
// Add dates from tomorrow until Sunday
do {
dates.push(new Date(year, month, ++day));
} while (dates[dates.length - 1].getDay());
return dates;
};
getDatesToSunday().forEach(d=>console.log(d.toDateString()));

javascript - date difference should be zero but it is 18 hours

This one has stumped me. It should be so simple I would think. I am doing some very simple date subtraction in Javascript. I am subtracting the same dates and I would think it would give zero hours, but it gives 18 hours.
let inDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime();
let outDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime();
document.getElementById('date').innerHTML = new Date(outDate - inDate);
<div id='date'>
</div>
In case it produces different results based on where you are, the result I am getting is this:
Wed Dec 31 1969 18:00:00 GMT-0600 (Central Standard Time)
This is due to your timezone. If you convert to GMT String before print it the time will be correct. (Jan 01, 1969 00:00:00)
new Date(outDate - inDate).toGMTString()
You should see the correct date.
let inDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime()
let outDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime()
console.log(new Date(inDate - outDate).toGMTString())

new Date() sets wrong month

I want to parse a string (or even the ints) at the new Date() function, but see what happens:
date = "2015-12-13"
"2015-12-13"
date
"2015-12-13"
date2 = new Date(date);
Sat Dec 12 2015 19:00:00 GMT-0500 (Hora est. Pacífico, Sudamérica)
date2 = new Date(2015,12,13);
Wed Jan 13 2016 00:00:00 GMT-0500 (Hora est. Pacífico, Sudamérica)
what could be wrong?
Month dates start at 0 in javascript, so 0 would be January and 11 would be December in your example.

javascript sometimes CET sometimes CEST

I've one script where I create two Date instance, the first return the date in CET offset timestamp and the second in CEST. I can't understand why.
var start_date = new Date(2014, 1, 26, 12, 0 , 0, 0);
var first_start_date = new Date(2014, 3, 1, 12, 0 , 0, 0);
return: Wed Feb 26 2014 12:00:00 GMT+0100 (CET) Tue Apr 01 2014 12:00:00 GMT+0200 (CEST)
I've also create a jsfiddle example
This is due to DST.
Also, see that CEST is Central European Summer Time.
It's just because April 1 is in Daylight Savings time (starts March 9th in the US this year), and February 26th is not in Daylight Savings time.

javascript Date library repeating October

While trying to find out why I was having issues while working on a calendar, I ran into this issue. When setting the month to 8, the date is set to October, when the month is set to 9, the date is set to October.
Code to test
var d = new Date();
document.write(d.getMonth());
d.setMonth(8);
document.write(d.getMonth());
d.setMonth(9);
document.write(d.getMonth());
output:
799
The current date is August 31st 2012, the month number should be 7, since the javascript months are 0 based.
Can someone explain this? I have been able to reproduce it on more than one computer.
September only has 30 days - when you set the day to 31 (or create a date on the 31st of some month) and then change the month to one with fewer than 31 days JavaScript rolls the date over into the next month (in this case October). In other words, the date overflows.
> var d = new Date()
> d
Fri Aug 31 2012 22:53:50 GMT-0400 (EDT)
// Set the month to September, leaving the day set to the 31st
> d.setMonth(8)
> d
Mon Oct 01 2012 22:53:50 GMT-0400 (EDT)
// Doing the same thing, changing the day first
> var d = new Date()
> d
Fri Aug 31 2012 22:53:50 GMT-0400 (EDT)
> d.setDate(30)
> d
Thu Aug 30 2012 22:53:50 GMT-0400 (EDT)
> d.setMonth(8)
Sun Sep 30 2012 22:53:50 GMT-0400 (EDT)
So the simple answer is, because the date for today is the 31st of August and the 31st of September is October 1st.

Categories

Resources