Difference in initialization of two dates in Javascript - javascript

Why do these two dates are differents :
var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setMonth(10); // month (from 0-11)
date1.setDate(1); // day of the month (from 1-31)
var date2 = new Date(2012, 10, 1, 0, 0, 0, 0);
Result :
Date 1 : Sat Dec 01 2012 14:56:16 GMT+0100
Date 2 : Thu Nov 01 2012 00:00:00 GMT+0100
whereas these two dates are equals :
var date3 = new Date();
date3.setFullYear(2012); // year (four digits)
date3.setMonth(9); // month (from 0-11)
date3.setDate(1); // day of the month (from 1-31)
var date4 = new Date(2012, 9, 1, 0, 0, 0, 0);
Result :
Date 3 : Mon Oct 01 2012 14:56:16 GMT+0200
Date 4 : Mon Oct 01 2012 00:00:00 GMT+0200
Another question is why do date1.setMonth(10) gives a date in December (should be November).

Finally got it. new Date() sets the date to the current date and time. In other words, October 31st (at the time of this writing).
When you then try to set the month to November, what's it to do? November only has 30 days... so it wraps it round to December.
If you change the order so that you set the day-of-month before the month, it works:
var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setDate(1); // day of the month (from 1-31)
date1.setMonth(10); // month (from 0-11)
Or as implied by jbabey's answer:
var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setMonth(10, 1); // month (from 0-11) and day (1-31)
The documentation isn't terribly clear, but it's at least suggestive:
If a parameter you specify is outside of the expected range, setMonth attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1 (year + 1), and 3 will be used for month.
("Accordingly" is far from precise, but it means the implementation is at least arguably correct...)

setMonth accepts a second parameter:
If you do not specify the dayValue parameter, the value returned from the getDate method is used.
When you set the month to 10 (November), it grabs the current day value (31) and sets that as the day. Since there are only 30 days in November, it rolls you over to December 1st.

You're creating a var containing the current date (new Date()) and then you're changing some of it's keys (year, month and day).
On the other hand new Date(2012, 10, 1, 0, 0, 0, 0) means "create a date object with those exact values".
And that's why your date objects aren't equal.

Related

How to get last day of previous month using current date?

I'm trying to get the last of day of previous month using the current date:
var myDate = new Date();
According to MDN:
if 0 is provided for dayValue, the date will be set to the last day of the previous month.
But when set date to zero:
myDate.setDate(0)
console.log(JSON.stringify(myDate));
I get "2021-08-01T01:18:34.021Z" which first day of the current month. What is wrong with this approach?
JSON.stringify() is serializing the timestamp with a Z timezone, indicating UTC. The difference between UTC and your local timezone is causing the date to rollover to the next day.
You can use toLocaleString() to print the date in your local timezone:
var myDate = new Date();
myDate.setDate(0);
console.log(myDate.toLocaleString());
I would use dateInstance.toString() or dateInstance.toLocaleString():
const myDate = new Date;
myDate.setDate(0); myDate.setHours(0, 0, 0, 0);
console.log(myDate.toString()); console.log(myDate.toLocaleString());
You can use date-fns package
var df = require("date-fns")
let myDate = new Date() //Thu Aug 05 2021 22:16:09
let lastDayOfPrevMonth = df.endOfMonth(df.subMonths(myDate, 1)) //Sat Jul 31 2021 23:59:59 GMT-0400

Get day/month from new Date(date) getting current day/month [duplicate]

This question already has answers here:
Date.getDay() javascript returns wrong day
(8 answers)
Closed 3 years ago.
I'm having trouble with new Date constructor,
when i set new Date(date) and ask console to print it, then it returns the date i want but if i try to get the day/month it returns my current day/month as if i was setting to new Date().getDay()
let date, end;
date = new Date()
end = new Date(date.getFullYear(), date.getMonth() + 1, 0)
console.log(end) // prints: Thu Oct 31 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)
console.log(end.getDay()) // prints: 4
I want the output to be 31 but it's not working, am i doing something wrong?
if you want to print the date (1-31) , you have to use the method getDate().
let date, end;
date = new Date()
end = new Date(date.getFullYear(), date.getMonth() + 1, 0)
console.log(end) // prints: Thu Oct 31 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)
console.log(end.getDate()) // prints: 31
I think you are using the wrong method
let end = new Date(date.getFullYear(), date.getMonth() + 1, 0)
console.log(end) // prints: Thu Oct 31 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)
console.log(end.getDay()) // Returns the day of the week
console.log(end.getDate()) // Returns the day of the month
getDay() doesn't return the number of the day in the month. It returns the day in the week.
Use getDate() for your desired return. Also you can check the document in here

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.

Why is .setUTCFullYear() and .setUTCMonth() return different results

In this sample code to convert a string to a date:
function stringToDate(){
var edate = "2015-06-01";
Logger.log(edate);
var input = edate.split('-');
var date = new Date();
date.setUTCFullYear(input[0],input[1] - 1,input[2]);
Logger.log(date);
}
Logging the date returns "Mon Jun 01 20:07:45 GMT+01:00 2015", which is correct, as the month '06' - 1 = 5 corresponds to the month of June for the this.
However, this almost identical function:
function stringToDate2(){
var edate = "2015-06-01";
Logger.log(edate);
var input = edate.split('-');
var date = new Date();
date.setUTCFullYear(input[0]);
date.setUTCMonth(input[1] - 1);
date.setUTCDate(input[2]);
Logger.log(date);
}
Returns "Wed Jul 01 20:10:04 GMT+01:00 2015". Some other values return equally screwy results. Why do I get a different result for 'setUTCMonth' then for 'setUTCFullYear'?
Set the Date before the Month
date.setUTCFullYear(input[0]);
date.setUTCDate(input[2]);
date.setUTCMonth(input[1] - 1);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth
If a parameter you specify is outside of the expected range,
setUTCMonth() attempts to update the date information in the Date
object accordingly. For example, if you use 15 for monthValue, the
year will be incremented by 1, and 3 will be used for month.
Each of the UTC functions has a similar note about out of range values.
So because of this:
new Date() gets the current date, and thus today being 5/31 the date is 31.
There are some months without a 31st date, so 31 is outside the range for date so it is updated accordingly.
So if you try to set the month for say February without changing the date first,
The date would be 2/31/2015, but February only has 28 days this year so it rolls over to 3/03/2015
And in your case, if you try to set it for June, 6/31/2015, June never has a 31st date so again it rolls over to 7/01/2015. And so on.
So change the date first like I show above or set a default date when you create it:
new Date("01/01/2015")

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