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.
Related
This question already has answers here:
How to check if date is within 30 days? [duplicate]
(2 answers)
Closed 4 years ago.
There is a problem when I set the maxdate based on current date.
Here is the code:
var minDate = new Date();
var maxDate = new Date();
function myFunction() {
maxDate.setDate(new Date().getDate() + 60);
document.getElementById("demo").innerHTML = maxDate;
}
<p>Click the button to display the maxDate</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
Everytime I click on a button date is increasing by 60 days.
I want to validate it with the date entered in date input, my validation is as below.
Date entered in input should be between current date and 60 days after current date.
Output:
On click of button.
1st Click : Tue Aug 28 2018 11:36:52 GMT+0530 (India Standard Time)
2nd Click : Sun Oct 28 2018 11:36:52 GMT+0530 (India Standard Time)
3rd Click : Fri Dec 28 2018 11:36:52 GMT+0530 (India Standard Time)
Please help.
new Date().getDate() returns the day of the month for current date according to local time - my current local date is 29 June 2018, so it returns 29.
That means that new Date().getDate() + 60 returns 89.
maxDate.setDate(89) sets the day of the maxDate object relative to the beginning of the currently set month.
maxDate is in global scope - that means currently set month in maxDate is changed after each click.
Try making maxDate local to your function:
function myFunction() {
let maxDate = new Date();
maxDate.setDate(new Date().getDate() + 60);
document.getElementById("demo").innerHTML = maxDate;
}
<p>Click the button to display the maxDate</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
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.
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.
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.
Consider the following code of HTML & JavaScript
<!DOCTYPE html>
<html>
<body>
<script>
var str = "20990229";
var showDate = new Date();
showDate.setFullYear(str.substring(0, 4))
showDate.setMonth(parseInt(str.substring(4, 6), 10) - 1)
showDate.setDate(str.substring(6, 8))
document.write(showDate)
</script>
</body>
</html>
Output:
Fri Mar 01 2099 16:02:52 GMT+0530 (India Standard Time)
The output is not the correct one, where I am going wrong is not known.
Could anyone tell me where I am going wrong?
The output is exactly as it should be:
var str = "20990229";
var showDate = new Date();
showDate.setFullYear(str.substring(0, 4)); // Set year to 2099
showDate.setMonth(parseInt(str.substring(4, 6), 10) - 1); // Set month to 1
showDate.setDate(str.substring(6, 8)); // Set date to 29
That would be 29th February 2099. (Note that months are indexed from 0).
Since 2099 is not a leap year there is no February 29th, and the date corresponds to March 1st.
If you change the year to one that is a leap year (such as 2096) then the output will be as you expect. Here's an example.