setMonth() setting wrong date in the case of 31st day [duplicate] - javascript

This question already has answers here:
`date.setMonth` causes the month to be set too high if `date` is at the end of the month
(8 answers)
Closed 1 year ago.
I am facing very strange behavior of setMonth function of JS.
On click of a image i am showing a calendar, having all days of current month and some next and previous month's date (in Grey color).
Whenever current date selected is 31st date of any month. suppose 31 may 2017 I select i will set in a textfield. If I click on 2 june 2017 rather then setting textfield to 2 june 2017 it sets 2 July 2017 ?
please suggest whats wrong is going here.
Code snippet used as follows
var tempDate = new Date(current); //Suppose : current --> Wed May 31 16:09:00 UTC+0530 2017
var dayOfMonth = parseInt(element.text(), 10); //Suppose : element.text() --> 2
tempDate.setMonth(tempDate.getMonth() + (dayOfMonth > 15 ? -1 : 1)); //tempDate.getMonth() + (dayOfMonth > 15 ? -1 : 1) returns 10
tempDate.setDate(dayOfMonth);
//Output Expected : 02 June 2017 but it gives 02 July 2017

In javascript date object, Month is starting form 0, so if you want to generate any month, then do accordingly. Refer this url for Date: MDN Date
As your code , I think you made mistake at
dayOfMonth > 15 ? 1 : -1
var dayOfMonth = 13;
alert((dayOfMonth > 15 ? 1 : -1))
var tempDate = new Date();
tempDate.setMonth(tempDate.getMonth() + (dayOfMonth > 15 ? 1 : -1));
tempDate.setDate(dayOfMonth);
alert(tempDate)

I think that is for the standard behavior of the operation when the month does not have the day (31) the operation take the next month that have that day
>var date = new Date('2018/10/31');
undefined
>date
Wed Oct 31 2018 00:00:00 GMT-0600 (hora estándar central)
>date.setMonth(date.getMonth() + 1);
1543644000000
>date
Sat Dec 01 2018 00:00:00 GMT-0600 (hora estándar central)

Related

Function returns incorrect month depending on order of statements

Does anyone have any thoughts on why this might have happened? Today, I found that a date conversion function I wrote started returning the wrong month. For instance, when attempting to convert "2017-06-02" to "Fri Jun 02 2017 00:00:00 GMT-0600 (Mountain Daylight Time)", it actually returned July instead of June. When I re-arranged the order of some of the statements in the function, the correct date was finally returned. This code has been in place for many months, so this spontaneous...maybe due to the current month changing, as today is 5/31/17? This might only be broken when ran on todays date, or end-of-month? (I'm sure there's a better way to convert dates, but here's the code in question anyway):
<!doctype html>
<body onload="testDate()">
<div id="resultbad"></div>
<div id="resultgood"></div>
<script>
function testDate() {
document.getElementById("resultbad").innerHTML = "Bad Result: Converting 2017-06-02 returns: " + badDate("2017-06-02");
//returns: Bad Result: Converting 2017-06-02 returns: Sun Jul 02 2017 00:00:00 GMT-0600 (Mountain Daylight Time)
document.getElementById("resultgood").innerHTML = "Good Result: Converting 2017-06-02 returns: " + goodDate("2017-06-02");
//returns: Good Result: Converting 2017-06-02 returns: Fri Jun 02 2017 00:00:00 GMT-0600 (Mountain Daylight Time)
}
function badDate(d) {
var td = d.split('-');
var nd = new Date();
//originally ordered: Year, Month then Day
nd.setFullYear(td[0]);
nd.setMonth(td[1] - 1);
nd.setDate(td[2]);
//set time
nd.setHours(0);
nd.setMinutes(0,0,0);
return nd;
}
function goodDate(d) {
var td = d.split('-');
var nd = new Date();
//new order: Day, Month then Year
nd.setDate(td[2]);
nd.setMonth(td[1] - 1);
nd.setFullYear(td[0]);
//set time
nd.setHours(0);
nd.setMinutes(0,0,0);
return nd;
}
</script>
</body>
This code overrides the date elements based on today's date. So, if you are running the code on the 31st day of the month, the "bad" version of this code will overwrite the month first, and if that month only has 30 days, it will roll over to the next month.
Basically, after setMonth but before setDate, you are trying to create the date June 31, 2017, which JS will convert for you into July 1, 2017.
Instead, do this as one call:
new Date(td[0], td[1]-1, td[2], 0, 0, 0, 0)
You figured out the problem fairly well - it has to do with today being the 31st of the month.
The issue is that new Date() creates a date object with the fields filled in. You're then changing those fields one by one.
So right now we can think of it as having a pseudo-structure like this, remembering that month is 0-based:
{
year: 2017
month: 4
date: 31
}
when you call setMonth(), you're just changing the month field, so you'd think for June it would set it to
{
year: 2017
month: 5
date: 31
}
but it knows there aren't 31 days in June. The 31st "day" of June would be the 1st of July. So it helps you out and adjusts it to
{
year: 2017
month: 6
date: 1
}
You're then setting the date to the 2nd with setDate():
{
year: 2017
month: 6
date: 2
}
In the function that works, you're setting the date before the month, so you're not having it recompute what the day is in case you've specified a date that is larger than the number of days in the month.

Javascript is giving invalid month when month is set to 5

I am getting invalid date when I set month as 5 in JavaScript date object.
I know that Month is zero based. so, month 5 means June.
But I am getting month as July.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date after changing the month.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo1"></p>
<p id="demo"></p>
<script>
function myFunction() {
var d = new Date();
d.setYear(2017);
d.setMonth(5);
d.setDate(30);
document.getElementById("demo1").innerHTML = d.getMonth();
document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>
Output:
6
Sun Jul 30 2017 15:11:20 GMT+0200 (W. Europe Daylight Time)
But, Ideally the output should be:
5
Sat Jun 30 2017 15:11:20 GMT+0200 (W. Europe Daylight Time)
Here is what happens:
var d = new Date();
//d is today : which is 31st of May (day of your test)
d.setMonth(5)
//5 is June (setMonth starts at 0)
//As 31st of June doesn't exist, it is set as 1st of July.
d.setDate(30)
//d is now 30th of July
You'd better use the full Date constructor:
new Date(year, month, date);
Today is May 31st 2017.
When you set the month to 5 which is June, the day is still 31 but there is no June 31. At this point behavior is undefined or at least unclear; anything could happen really.
To avoid it, create the date like this:
var date = new Date(2017, 5, 30);
This is because setMonth will also set the day, but we are on 31 and June only contains 30 days, so the date will change to 1 July. Then on July 30th thanks to the setDay. Try to set the day before, normally it should work.

Why is this momentjs date incorrect?

Here is my code:
var moment = require("moment");
var day = 31;
var month = 12;
var year = 2016;
moment().date(day).month(month - 1).year(year)
The date that is returned is Sat Dec 03 2016 16:23:43 GMT-0700 (MST).
Why is the date being converted to 03 instead of 31?
This line is processed in multiple steps: moment().date(day).month(month - 1).year(year)
First: moment().date(31)
It is currently February 7th, 2017. We are changing it to "February 31st, 2017", which wraps around to March 3rd since February has only 28 days.
Then it changes the month to 12, and the year to 2016.
Flip the steps around. Do the year first, then month, then date.

Why this datetime funtion setMonth result is wrong? getMonth() + 1

I have this code:
var nextDate = new Date("2016 01 31");
nextDate.setMonth(nextDate.getMonth() + 1);
I'm expecting the result to be Feb 28 2016, but it shows Mar 02 2016 instead.
Why? Is there any solution for it?
There is only 29 day in February, therefore, February 31 February will translate to Mars 2.
You need to update the days in your date object to the last day of that month. You can get the last day of the month by specifying a function that sets the date to 0:
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
This is because February has 29 days, and when you set new month from January, which has 31 day, to February then the difference of the days are transferred to another month.
Easy way to do it is just create new Date instance.
You might need to implement some logic to get corresponding dates right
Possible work around with a helper function: after setMonth, check if the results doesn't contain a month equal to the expected month and if so, use setDate(0), which sets the date to last day of the previous month. e.g.
Date.prototype.addMonths = function(months){
var m = this.getMonth() + (months || 1);
this.setMonth(m);
if(this.getMonth() !== (m % 11)) //11: month is 0 based
this.setDate(0);
}
var nextDate = new Date("2016 01 31");
nextDate.addMonths(1);
document.writeln(nextDate);
months || 1 only is meant to have a default value if no month was submitted. m % 11 is needed in case of year transitions. 11 and not 12 because javascripts month (and thus getMonth) is 0 based.

Time differences wrong calculation

function parseDate(s){
var parts = s.split('/')
return new Date(parts[2], parts[1], parts[0])
}
function calcDaysBetween(startDate, endDate){
return Math.floor((endDate-startDate)/86400000);
}
function yarro(){
var startDate = parseDate($('#pickupdate').val());
var endDate = parseDate($('#dropoffdate').val());
var days = calcDaysBetween(startDate, endDate);
$('#newp').html('Days Count: <b>'+days);
}
31/3/2012 , 1/4/2012
Days Count: 0 //wrong
or
31/1/2012 , 1/2/2012
Days Count: -1 //wrong
1/1/2012 , 2/1/2012
Days Count: 1 //ok
Why?
Knowing that JS months are 0-based is very important to this. Your code is parsing the date 31/1/2012 into 31 February 2012, which is technically an invalid date but is interpreted as 2 March 2012 (the 2nd because 2012 is a leap year). What you need to do is subtract 1 from the parts[1] value before passing it to the Date constructor.
You are getting -1 days between 31/1/2012 and 1/2/2012 because those dates are interpreted as 31 February 2012 (2 March 2012) and 1 March 2012. When you subtract those dates, you get a -1-day difference.
You are getting 0 days between 31/3/2012 and 1/4/2012 because those dates are interpreted as 31 April 2012 (1 May 2012) and 1 May 2012, which are the same date, resulting in a 0-day difference.
You are getting 1 day between 1/1/2012 and 2/1/2012 because those dates are interpreted as 1 February 2012 and 2 February 2012, resulting in a 1-day difference.

Categories