JavaScript date math not working - javascript

I have searched this forum and found many useful answers, but one of the answers that I used only works under certain conditions.
I am populating a week calendar, and simply need to determine the start of the week (Monday) from a Date picker, and then I add to that date to populate text fields with the following 6 days. This works only if the date picker selection is in the same month.
So, if I select Wednesday May 15th 2013, it correctly returns and populates the Monday with May 13, the Tuesday with May 14, etc.
But, if I select Wednesday May 1, 2013, it correctly populates Monday Apr 29, but Tuesday it puts as May 30 (adding a month instead of a day).
I should note that I am building this in Application Craft, so I don't know if that has any impact.
Here's my code:
var curr = new Date(app.getValue("DatePicker2")); // get selected date
var first = curr.getDate() - curr.getDay() +1; // Adjust for monday start of week
var firstday = new Date(curr.setDate(first));
var secondday = new Date();
secondday.setDate(firstday.getDate()+1);
Can anyone see where I have gone wrong?
Thanks
Tammy

Here
secondday.setDate(firstday.getDate()+1)
since you are specifying only the date in the setDate function, it would assume "this" month which happens to be May in this case
So, you can do
secondday = new Date(firstday.getFullYear(), firstday.getMonth(), firstday.getDate()+1)

Related

How can I get the dates for the current week in JavaScript?

I'd like to be able to get the first and the last date of the current week. For example, this week would be September 4th to September 10th.
The issue I'm running into happens at the end of the month when there are dates from two months (like the last month of August). This caused a problem because the date range was displayed as August 28th to August 3rd when it should've been September 3rd.
I saw some other posts recommending Moment.js, but the Docs say that it shouldn't be used in new projects. What's a good way to do this?
Get the current date: const start = new Date();
Shift that back by the current day-of-week: start.setDate(start.getDate() - start.getDay());
Make a new date based on that: const end = new Date(start);
Shift that date forward: end.setDate(end.getDate() + 6);
That will give you a Sunday to Saturday week. You can shift the days as necessary based on what you consider a "week" to be.
The JavaScript Date API will deal with month shifts automatically. Thus if it's Thursday September 1, moving the day-of-month back to Sunday will correctly give the date in August.

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

javascript: fetch day of the week based on a specific date

I searched stackoverflow but did not find a solution to my problem.
I have a specific date say 2014-05-20 and I want to get the Day of the week for the mentioned date.
I tried the following
var date = new Date();
console.log(date.getDay());
But this return the Current Day. What I require is the day based on the given date!
I also tried
var givendate = '2014-05-20';
new Date(givendate)
But the above does not generate anything.
Your question both code you combine and check answer is get on yourself without my answer still i show you code,
Check this Demo jsFiddle
JavaScript
var givendate = '2014-05-20';
var date = new Date(givendate);
console.log(date.getDay());
Console log
2
you may try
var date = new Date(2014, 05, 20).getDay(); // Date(year, month, date)
console.log(date);
you will get integer 0 for sunday - 6 for saturday

JavaScript Countdown Time

I'm using this plugin to do a countdown. In his example, he is counting down to Australia Day
$(function () {
var countdownDate = new Date();
countdownDate = new Date(countdownDate.getFullYear() + 1, 1 - 1, 26);
$('#countdown').countdown({until: countdownDate});
$('#year').text(countdownDate.getFullYear());
});
I need it to count down to 8 PM EST on Tuesday, November 6, 2012, but I'm not sure how to customize it. The Date() function confuses me.
The Date constructor shown above is in the format new Date(Year, Month, Day). However, keep in mind that the Month argument is 0-indexed. That means that January is 0, not 1. So to count down to November 6th, 2012, you would want to construct the date like this:
countdownDate = new Date(2012, 10, 6);
You might also consider doing:
countdownDate = new Date(2012, 11-1, 6);
Which is similar to what the example shows. But it just slows things down unnecessarily in order to be more clear about what month you're referring to.
Additionally, if you construct a Date object with no arguments, it gives you the current date. So new Date() gives you a date object equivalent to "now". In the example, they use that to get the current year using (effectively) (new Date()).getFullYear(). They then increment it by one and pass it into a new Date constructor in order to get the time until the "next" Australia Day.
It should be noted that the Australia Day example actually has a bug. If it's currently January, then the year will be unnecessarily incremented and the countdown will show the time until the following year's Australia Day. So in the example, the countdown will never drop below 26 days. Whoops. :-)
UPDATE:
Either your question got updated or I missed this the first time around. Looks like you wanted to end at 8PM EST. That's actually pretty tricky using the numerical date constructor. Because JavaScript runs on the client side and uses "local time" by default, you need to explicitly note the time zone. You can do this using the setUTC versions of setters (e.g. setUTCHours()), but it's a bit annoying and takes several lines of code. So your best bet is to use Date's String-based constructor:
new Date("November 6, 2012 20:00:00 GMT -5:00")
The Date() constuctor calls you'd want to use would be one of the following:
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Soy, you could do
new Date("November 6, 2012 20:00:00 GMT -5:00")
and that would do it.
countdownDate = new Date(2012, 10, 6, 20, 0, 0, 0);
or
countdownDate = new Date("11/6/2012 8:00 PM")
see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
These lines determine the date that it's counting down to:
var countdownDate = new Date();
countdownDate = new Date(countdownDate.getFullYear() + 1, 1 - 1, 26);
The first line here creates a new JavaScript Date Object. It defaults to right now when you create a Date.
The next line sets the date to a specific point in time using the structure:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
I'll go one step at a time:
1. Year it gets the current year with countdownDate.getFullYear(), add one to make it next year
2. 1 - 1 = 0, so this is selecting the first month (January)
3. 26 is the 26th day of a particular month
To fix you can replace both of these lines with a single one using the string notation:
var countdownDate = new Date("November 6, 2012 20:00:00 EST");

Javascript date, is this my error or did I find a bug?

I have a section of simple Javascript in my application that has a link "Add Day", which adds 1 day to a date. It always works perfectly, except when the date gets to be 11/07/2010, and then the link suddenly will not work any longer. Its really wierd, because it only hangs up on the specific date of 11/07/2010.
How to reproduce error:
Navigate to the page here
On any date field, click "Today", or just set the date to today.
Click "Add Day" until you get to 11/07/2010
Now clicking "Add Day" does not work anymore!
The problem is that you're adding the 24 hours to the date to add one day; Daylight Savings Time has thwarted you because 24 hours after 00:00 on November 7th will be 23:00 (for the second time) on November 7th.
Others spotted what the problem is.
To fix it you can use the overloaded Date constructor that takes the year, month, and day:
var aDate = new Date(2010, 10, 07);
var aDatePlusOneDay = new Date(aDate.getFullYear(),
aDate.getMonth(),
aDate.getDate() + 1, // HERE
aDate.getHours(),
aDate.getMinutes(),
aDate.getSeconds(),
aDate.getMilliseconds());
Here's a more generic solution that can increment any date by a given millisecond amount, taking changes to daylight savings into account:
Date.addTicks = function(date, ticks) {
var newDate = new Date(date.getTime() + ticks);
var tzOffsetDelta = newDate.getTimezoneOffset() - date.getTimezoneOffset();
return new Date(newDate.getTime() + tzOffsetDelta * 60000);
}
Adding a day to a Date object then is a matter of adding the number of milliseconds in one day:
Date.addTicks(new Date(2010, 10, 7), 86400000); // new Date(2010, 10, 8)
References:
Date.prototype.getTimezoneOffset
Daylight Savings Time. (In most places in the US) the time rolls back on the first Sunday of November. Your code is just adding an amount of milliseconds to the start of the day specified by the input box, and the returning the beginning of the resulting day: however because of DST, simply adding seconds and truncating the date this way will never progress the date.

Categories