I need some help with javascript dates. I have found a bug when I was working. I think that it has been solved but I don't know why.
We have a custom calendar with seven days each pages (monday-sunday).
When you pick next (>) it add 7 days. The trouble was that in october 2015 (19-25) when you pressed next, it becomes a new week with days between 25-31 instead of 26-1 week.
This was the code that sum one week:
date = new Date( date.getTime() + num * 86400000 );`
And this is how I "fix" it:
date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + num);`
Now the picker is working, I suppose 86400000 are the milliseconds in a day but why it doesn't work for some days?
Thanks
Late October in your locale is when Daylight Savings or "Summer" time ends. One of the days in that week is slightly shorter than other days.
The internals of the JavaScript runtime know about that, so adding days via the setDate() API gets the right answer.
If I may make a recommendation: check out Moment.js. While it doesn't directly answer your question as to why you're encountering your issue (#Pointy's answer is right), it will make such calculations such as yours much simpler.
Instead of this:
date = new Date( date.getTime() + num * 86400000 );
You can do this:
date = moment().add(1, 'w').toDate()
...and I believe it will account for daylight savings time.
Related
I'm trying to calculate the time until the US/Central midnight. The problem is that my calculation returns 3 hours 30 minutes (as for me in Europe it's 20:30).
moment('2020-12-19 23:59:59', "YYYY-MM-DD HH:mm:ss", 'US/Central') - moment.tz('US/Central')
I think this should work. I'm calculating a difference between US/Central midnight and US/Central now, but it returns the wrong amount of milliseconds.
Do you know how to make it work?
EDIT:
Tried it with diff and still the same result:
moment('2020-12-19 23:59:59', "YYYY-MM-DD HH:mm:ss", 'US/Central').diff(moment.tz('US/Central'),'hours')
> 3
EDIT2:
Tried moment().tz instead of moment.tz and it didn't help at all...
moment('2020-12-19 23:59:59', "YYYY-MM-DD HH:mm:ss", 'US/Central').diff(moment().tz('US/Central'),'hours')
> 3
Maybe try getting the 2 times separately then find another way to check the difference between them. For example
var now = new Date();
var midnight = new Date();
midnight.setHours(0,0,0,0); // this set's the midnight var to exactly midnight at your systems timezone, you can then offset that time after this
Then use either moment or some other package to check the difference between the two times.
So I am kinda stuck in figuring out a certain aspect. What I want to do is the following:
Let's say I just have a simple date display, which will show a date such as October 10th, 2017 to an end user. And then there is an option to subtract a certain number of days from said date (an offset of 1, 2, 3, whatever offset is chosen).
What I am looking to do is completely exclude weekend dates from the count - so if today is Monday, October 9th, and an offset of 1 is selected, it goes to Friday the 6th; if an offset of 2 is chosen, it goes to Thursday the 5th; an offset of 3 goes to Wednesday the 4th...
If today was Wednesday, October 11th, an offset of 2 would take you to Monday the 9th, an offset of 4 would go to Thursday the 5th, and so on (completely disregards / skips weekend dates when counting / subtracting which day to land on).
I have so far been able to only find answers for the functionality to calculate the number of working days excluding weekends, and things of that nature (which I already have, using the momentjs-business npm module, but is not exactly what I need).
I did not post code because this is part of a much larger code base, and I feel posting snippets would only add to the confusion, since I believe the question is relatively simply and straightforward; I do not want to over complicate.
All I would like is to not include weekends at all when setting an offset from whichever date is displayed to the user (the date which is displayed to the user is from a database).
I hope this all made sense, and if more info is needed, please let me know. Thanks in advance for anyone that can point me in the right direction!
This will achieve what you want I think. Please note this is terribly inefficient. If your offset is very large it generates a new date every iteration of the loop. With some tinkering it could be optimized
let startDate = new Date('10/10/2017');
let endDate = "", offset = 2;
while(offset > 0){
endDate = new Date(startDate.setDate(startDate.getDate() - 1));
if(endDate.getDay() !== 0 && endDate.getDay() !== 6){
offset--;
}
}
Here is a working Fiddle
You can use moment-business library. It has the subtractWeekDays that:
Subtract week days from the moment, modifying the original moment. Returns the moment.
Your code could be like the following:
var m = moment("October 10th, 2017", "MMMM Do, YYYY");
business.subtractWeekDays(m, 2);
If you don't want to add an external library, have a look at addWeekDays and subtractWeekDays code.
JavaScript date objects have a getDay() method that tells you what day of the week it is. You could use this to figure out which dates are weekends and exclude them.
var date = new Date();
var dayOfWeek = date.getDay();
console.log(dayOfWeek) // 1 for Monday, 2 for Tuesday, etc.
So I'm trying to use a javascript date object to deal with automatically rolling over the days. However getting the information seems to be difficult.
date = new Date();
console.log(date.toISOString());
date.setTime(date.getTime() + 600000); // 10 minutes
console.log(date.toISOString());
console.log(date.getDay());
console.log(date.getUTCDay());
This returns
"2014-10-23T22:55:34.962Z"
"2014-10-23T23:05:34.962Z"
4
4
I have no idea why it keeps returning a day that is not even close to what the day actually is.
My current solution just takes sections of the toISOString and assigns things bassed off of that, but I do want to know why this is doing this.
Day returns the day of the week, try date instead.
whats the best way to get previous sunday using new Date()?
any ideas? sorry newbie here*
Since it's not a trivial task, here's the algorithm I suggest for you:
Create a Date object
Get the current day of week from the object
If it's zero (Sunday) set it to seven
Subtract that many days from the date*
Done!
*This works really well thanks to some rather clever implementation. If you subtract 4 days from February 2nd, the result is January 29th.
Now it's up to you to write some code ;)
Many tutorials on the web will show you how to use Date.getDay() that returns the day of the week (from 0 to 6).
Then substract one day to your date until you get the expected result.
Here is my variant:
var dateNow = new Date();
var dateToday = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate());
var dateSunday = new Date(dateToday.getTime()-dateToday.getDay()*24*3600*1000);
in dateSunday you'll get date object on sunday start.
var yourDate = new Date(Date.now() - ((new Date().getDay() + 7) * 24 * 60 * 60 * 1000));
Date.now() gets the current date down to the millisecond, which makes it easy to perform mathematical calculations.
new Date().getDay() + 7, like one of the previous posters suggested finds the current day (0-based) and add 7 to that in order to subtract however many days we are from the most recent sunday, minus one week.
24 * 60 * 60 * 1000 ensures that we are subtracting that many full days (in milliseconds) away from our current day in order to find last Sunday.
Or, you could write some algorithm too.
Best of luck friendo. :]
I'm working on a jQuery credit card expiration date validation script. Credit cards expire after the last day of the expiration month. For instance, if the card expires on 8/2013 then it's good through 8/31/2013.
In the past on the server side I've determined the last day of the month by adding 1 to the current month, then subtracting 1 day.
Today I noticed that when creating a new date, if 0 is applied to the 3rd parameter of the JavaScript Date() object, the resulting date will be the end-of-month day. But I've been unable to locate any online documentation to affirm this observation.
Here is some sample code.
var month = 10;
var year = 2013;
var expires = new Date(year, month, 0);
alert(expires);
And here is a jsFiddle example that I created.
This is a bit confusing, because I thought in JavaScript months were zero based. I've tested this in Chrome, Firefox, IE, and Safari, and the behavior appears consistent. The returned date consistently displays the last day of the month. This looks like a lucky find, but I'd really like to understand what is happening here.
Am I safe to run with this approach to assigning an end of month date, and if so is there some online documentation that I can point to which affirms this? Thanks.
Months are zero-based. That creates an end-of-month date in the previous month. Month 10 is November, so creating a date with day 0 in November gives you the end of October (month 9).
That is, day 0 in November means "the day before 1 November", which is the last day of October. Day -1 in November would be 30 October.