javascript january date issue - javascript

function datecheck(){
var dt1 = new Date();
dt1.setUTCFullYear("2017");
dt1.setUTCDate("1");
dt1.setUTCMonth("1");
alert(dt1.getUTCMonth());
}
When I execute this function I am getting 0 as alert but if setUTCMonth("2"). I am getting 2 in alert. Similarly if 3,4,5,6,7,8... is given then it alerts with same month that is passed then what is problem with January month?
But also I have observed that if
function datecheck(){
var dt1 = new Date();
dt1.setUTCFullYear("2017");
dt1.setUTCMonth("1");
dt1.setUTCDate("1");
alert(dt1.getUTCMonth());
}
Behaviour change it start alerting 0 when 1 is passed. I am totally confused what is going on...
Can anyone tell me where I am going wrong.
Thanks in advance.

You have a couple of problems. First off, mutating Date objects that way is inadvisable unless you really know what you are doing. Its better to pass the desired parameters to the constructor:
var jan1 = new Date(2017, 0, 1);
Note that I passed in zero. That's because unlike every other date-related counting, in JavaScript months go from 0-11.
Secondly, you are ignoring the impact of timezones. JavaScript constructs Date objects in the local timezone. For example, I'm GMT -5 at the moment.
If I do the following in my browser's console:
var dec31 = new Date(2016, 11, 31, 20); // 20hr == 8pm
dec31.getMonth(); // 11
dec31.getUTCMonth(); // 0
The five hour offset pushes the UTC time into the next month.

Related

get last date of year of a given date

var reportDateStr = "2018-05-21";
var reportDate = new Date(reportDateStr);
var y = reportDate.getFullYear();
var lastDateOfReportYear = new Date(reportDate.getFullYear(), 11, 31);
console.log(lastDateOfReportYear)
Instead of getting the last day of the year 2018 which is Dec 31, 2018, I am getting Jan 31, 2019
Please, can you tell me what is wrong with the above code and why I am getting Jan 31, 2019?
To be honest, without digging deeper into what browser/node version you are using (we will get to why that matters in a moment), I am a bit uncertain as to why you are getting a date a month later (Jan 1, 2019 would make much more sense for the issue you are running into) but I will give a higher level explanation for why Jan 1, 2019 might be happening.
From the Date documentation:
Note: Where Date is called as a constructor with more than one argument, the specified arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.
So because your are constructing a new date with three parameters, the date represents your local time.
const localDate = new Date(2018, 11, 31);
console.log({
localDate // in EST this will be "2018-12-31T05:00:00.000Z"
});
Notice the hours is "05" (for EST) and not "00". Using Date.UTC as recommended will make it "00" regardless of local time.
const localDate = new Date(Date.UTC(2018, 11, 31));
console.log({
localDate // This will always be "2018-12-31T00:00:00.000Z"
});
A few other things to note when creating a Date from a date string (which is not recommended):
Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
So the date generated can be different due to various JavaScript implementations. Check out this chart for a reference on this issue.
Also note that getFullYearuses the local time to get the full year value. This can impact your desired output as well.
So, to be a bit more safe you could use UTC for all of your calculations:
const reportDateStr = '2018-05-21';
const reportDate = new Date(reportDateStr); // This could still be problematic
const y = reportDate.getUTCFullYear();
const lastDateOfReportYear = new Date(Date.UTC(y, 11, 31));
console.log(lastDateOfReportYear.toUTCString());
There are also libs like moment.js that can help with the multitude of issues dealing with times and dates.
You are doing too much work in something is always going to be the same.
December ALWAYS is going to be 31 days and the last month of the year is always going to be december, so why dont you just get the year and append to it 12-31
Example:
var reportDateStr="2018-05-21";
console.log(reportDateStr.substr(0,4)+'-12-31')
Now, If you want to keep your function make sure the TimeZone where you are. Your code works fine with the Eastern Time
See the working snippet below,
I added some consoling from your code and comments to make it simple:
var reportDateStr = "2018-05-21";
var reportDate = new Date(reportDateStr);
var y = reportDate.getFullYear();
var lastDateOfReportYear = new Date(y , 11, 31);
// For me the below returns the 30th December, 11pm
console.log('Date:', lastDateOfReportYear);
// … because I've got -120 as offset!
console.log('TimezoneOffset:', new Date().getTimezoneOffset());
// You need to use this one to get rid of the Timezones:
var lastDateOfReportYear_2 = new Date(Date.UTC(y , 11, 31));
console.log('Date UTC:', lastDateOfReportYear_2);
Hope it helps.

Adding a Date in Javascript

I'm trying to use the pattern described here: How to add number of days to today's date?
My goal is to start an animation at a date one week before a certain event, in this case the launch of Sputnik. My code is:
var SputnikLaunchDate = new Date(1957, 9, 4); //The first event of insterest in the simulation.
var earliestAnimationDate = new Date();
earliestAnimationDate.setDate(SputnikLaunchDate.getDate() - 7); //Start 1 week before then
When I do this in the Firefox debugger, the variable SputnikLauchDate is correct (1957-10-04T05:00:00.000Z). However, earliestAnimationDate ends up being 2015-05-28T18:49:54.313Z and I have no idea why. Can someone explain to me what I'm doing wrong?
The problem is that setDate sets the number of days relative to the current time, but when you constructed earliestAnimationDate you didn't give it any information, so it was set to today's date. Pass in SputnikLaunchDate.getTime() to initially copy that time into earliestAnimationDate (or else just put new Date(1957, 9, 4) again, of course).
var SputnikLaunchDate = new Date(1957, 9, 4);
var earliestAnimationDate = new Date(SputnikLaunchDate.getTime());
earliestAnimationDate.setDate(SputnikLaunchDate.getDate() - 7);

Calculate difference between 2 dates considering Daylight Saving Time

Given a start date, and a number of days, I need to display the end date = start date + number of days.
So I did something like this:
var endDate=new Date(startDate.getTime()+ONE_DAY);
Everything works fine, except that for 25 and 26 October gives one day less.
Ex.:
2014-01-01 + 2 days = 2014-01-03
2014-10-25 + 2 days = 2014-10-26 (here is the case I need to treat).
This difference appear because of the clock going back 1 hour. Practically 2014-10-27 00:00:00 becomes 2014-10-26 23:00:00.
A simple solution would be to compute this at another hour (example 3 AM). But I want to just display a note when this happens.
For example, if user inputs 2014-10-25, I show a popup saying [something].
Now here is the real problem... I can't seem to find any algorithm that says when clocks goes back in year X.
Example... in 2014 the day is 26 October. In 2016 is 30 October (https://www.gov.uk/when-do-the-clocks-change). Why? This date looks random to be, but I don't think it is. So... when does clock go back/forward?
EDIT: All answers/comments are helpful related to how to fix the problem. But... I already passed that stage. Now I only have an itch about "how on earth are the days when clock is changed computed?".
To find the difference between two dates in whole days, create Date objects, subtract one from the other, then divide by the milliseconds in one day and round. The remainder will only be out by 1 hour for daylight saving so will round to the right value.
You may also need a small function to convert strings to Dates:
// Return Date given ISO date as yyyy-mm-dd
function parseISODate(ds) {
var d = ds.split(/\D/);
return new Date(d[0], --d[1], d[2]);
}
Get the difference in days:
function dateDiff(d0, d1) {
return Math.round((d1 - d0)/8.64e7);
}
// 297
console.log(dateDiff(parseISODate('2014-01-01'), parseISODate('2014-10-25')));
If you want to add days to a date, do something like:
// Add 2 days to 2014-10-25
var d = new Date(2014, 9, 25);
d.setDate(d.getDate() + 2);
console.log(d); // 2014-10-27
The built–in Date object takes account of daylight saving (thought there are bugs in some browsers).
I prefer adding days this way:
var startDate = //someDate;
var endDate = new Date(startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()+1);
This way you don't have to worry about the days in the calendar.
This code add 1 day, if you want to add more, change the startDate.getDate()+1 for startDate.getDate()+NUMBER_OF_DAYS it works fine even if you are on the last day of month i.e. October 31th.
But maybe you can use #RobG solution which is more elegant than mine

why javascript's .getTime() + 24*60*60*1000 get's stack after 27 Oct 2013?

I was just creating a simple calendar when users clicks next it gets the following day, very simple code:
var dateSelected = new Date('02/06/2013'); //any date
var day = new Date(dateSelected.getTime() + 24*60*60*1000);
alert(day.getDate());
that works great for all dates but for some reason it doesn't get the next day when the date is 27 Oct 2013
var dateSelected = new Date('10/27/2013');
I don't seem to be able to figure out why, if I go manually to the next day 28 Oct it keeps working fine.
Any ideas why this happens?
UPDATE:
I fixed it by adding the time as well as the date:
var dateSelected = new Date('10/27/2013 12:00:00');
I strongly suspect this is because of your time zone - which we don't know, unfortunately.
On October 27th 2013, many time zones "fall back" an hour - which means the day is effectively 25 hours long. Thus, adding 24 hours to your original value doesn't change day if it started within the first hour of the day.
Fundamentally, you need to work out whether you're actually trying to add a day or add 24 hours - they're not the same thing. You also need to work out which time zone you're interested in. Unfortunately I don't know much about Javascripts date/time API, but this is almost certainly the cause of the problem.
Rather than adding the number of milliseconds in a day, you can use the set date function directly.
var dateSelected = new Date('10/27/2013');
var daysToAdd = 1;
var nextDay = new Date(dateSelected.getTime());
nextDay.setDate(dateSelected.getDate() + daysToAdd);
This also works when rolling over to the next month, and should work well with different time zones.
As Jon Skeet already mentioned, the problem results from your local timezone. As a possible solution, you can use the setDate and getDate functions of the Date object:
var dateSelected = new Date('02/06/2013'); //any date
dateSelected.setDate(dateSelected.getDate() + 1);
alert(dateSelected.getDate());
And of course, no JavaScript Date question could be complete without a Moment.js answer:
var m = moment('10/27/2013','MM/DD/YYYY').add('days', 1);
Superior API every time. :-)

Comparing today's date with another date in moment is returning the wrong date, why?

I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');

Categories