Here's the code :
var date = new Date(annee, mois, jour);
var i = 0;
while (i < 365) {
date.setTime(date.getTime()-(1000*60*60*24*i));
console.log(date.getFullYear()+'/'+parseInt(date.getMonth()+1)+'/'+date.getDate());
i++;
}
I'm trying to substract 1 day per loop, but i get this :
2016/1/13
2016/1/11
2016/1/8
2016/1/4
2015/12/30
2015/12/24
2015/12/17
2015/12/9
2015/11/30
2015/11/20
[...]
1834/2/27
after a quick look on stack's solution, I found this : Finding date by subtracting X number of days from a particular date in Javascript But the result is always a bunch of false days ...
I tried by getDate()-days, setTime(getTime()-(different ms calculs)) - as in code -, trying with utc gmt and iso ...
well ... hope someone can help me :/ thanks !
Remove multiplication by i. It subtracts i days.
var date = new Date(annee, mois, jour);
var i = 0;
while (i < 365) {
date.setTime(date.getTime()-(1000*60*60*24)); //removed *i
console.log(date.getFullYear()+'/'+parseInt(date.getMonth()+1)+'/'+date.getDate());
i++;
}
Dates are really hard. Even though it seems like an easy calculation, what happens if the date is the first of the month - would you expect the date to rollback to the last month? What if it is the first day of the year? Or the 1st March and it is a leap year?
I'd recommend deferring tasks like this to a library such as http://momentjs.com/ or http://sugarjs.com/dates.
Related
I have an interesting result from the javascript in an Acrobat PDF Form
I have a series of date form fields. The first field is for user entry and the remaining fields are calculated by javascript, each field incremented by one day.
The code is:
var strStart = this.getField("userField").value;
if(strStart.length > 0) {
var dateStart = util.scand("dd/mm/yy",strStart);
var dateStartMilli = dateStart.getTime();
var oneDay = 24 * 60 * 60 * 1000 * 1; // number of milliseconds in one day
var dateMilli = dateStartMilli + oneDay;
var date = new Date(dateMilli);
event.value = util.printd("dd/mm/yy",date);
} else { event.value = "" }
The issue is if I input 05/04/15 in to the user field the result is 05/04/15 (same, wrong) while any other date of the year correctly increments by one day (ie 25/10/15 gives 26/10/15, 14/2/15 gives 15/2/15 etc)
The same error occurs on the 3rd of April 2016, 2nd of April 2017, etc (ie each year)
I have a fortnight (14) of these incrementing fields, each incrementing the date from the previous calculated field with the same javascript as above ("userField" is changed to date2, date3, date4 etc). What is very strange is that the next field that increments off the second of the two 05/04/15 correctly returns 06/04/15 and there isn't an issue after that.
Does anyone know why this might be?!
That doesn't happen on my browser's JavaScript engine and/or in my locale, so it must be an Acrobat thing or that date may be special in your locale (e.g., DST).
In any case, that's not the correct way to add one day to a JavaScript date, not least because some days have more than that many milliseconds and some have less (transitioning to and from DST).
The correct way is to use getDate and setDate:
var strStart = this.getField("userField").value;
if(strStart.length > 0) {
var dateStart = util.scand("dd/mm/yy",strStart);
dateStart.setDate(dateStart.getDate() + 1); // Add one day
event.value = util.printd("dd/mm/yy",dateStart);
} else { event.value = "" }
setDate is smart enough to handle it if you go past the end of the month (per specification).
If it's DST-related, the above will fix it. If it's some weird Acrobat thing, perhaps it will work around it. Either way, it's how this should be done.
Let me guess, that's the day daylight savings starts in your locale? 24 hours after midnight is not always the next day, because some days have 25 hours.
Approaches that come to my head:
manipulate the day. (This is easy if Acrobat allows dates like the 32nd of January, because oyu can just increment the day. Otherwise, maybe don't bother because leap years aren't much better than DST.)
don't start from midnight. If you never use the hour and minute within the day, don't pin your day at the strike of midnight, but at, say, 3am. After a change in DST status, later days in your fortnight might register as 2am or 4am, but as long as you're only using the day…
I want to count down the days until a particular event using momentjs but I'm getting an unexpected result.
With today's date being 17th April, and the event date being 14th May, I want the resulting number of days to be 27, however my code gives me a result of 57. What's wrong?
function daysRemaining() {
var eventdate = moment([2015, 5, 14]);
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());
When creating a moment object using an array, you have to take note that months, hours, minutes, seconds, and milliseconds are all zero indexed. Years and days of the month are 1 indexed. This is to mirror the native Date parameters.
Reference
So either change the month to 4 to reflect May or parse the date as an ISO 8601 string
function daysRemaining() {
var eventdate = moment("2015-05-14");
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());
Just to add for anyone else that comes across this - there's actually a helper that does the phrasing etc for you:
https://momentjs.com/docs/#/displaying/to/
/* Retrieve a string describing the time from now to the provided date */
daysUntil: function(dateToCheckAgainst){
return new moment().to(moment(dateToCheckAgainst));
}
// Sample outputs
"in three months"
"in two months"
"in 25 days"
That's because months are zero indexed. So 5 is actually June ;)
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
I have been trying to make a quick reference sheet to use for work, and have been using this as a way to start trying to learn JavaScript.
I've been stumped on how to display the date in dd/mm/yyyy for the 4th Friday (or any day) from the current date. If anyone can point me in the right direction it would be greatly appreciated
The idea is to use setDate() for date addition. The following code should set you there:
<html>
<script>
// You might want to make a function out of this, btw.
dayWeWant = 5; // Friday
today = new Date();
// So you want the fourth friday, eh?
// remember friday is 5 for getDay
if (today.getDay() < dayWeWant) { nextFri = 7 - (today.getDay() - dayWeWant) } // days remaining
else { nextFri = dayWeWant - today.getDay(); }
// If today IS friday, you want 4 instead of 3. Of course,
// 3 can also be made into a "constant" variable, such as howManyWeeks or something
threeMore = nextFri + 3 * 7; // three more weeks
nextDate = new Date();
nextDate.setDate(today.getDate() + threeMore);
alert (nextDate);
</script>
</html>
Code is intentionally well annotated and not as efficient it can be (and the constant numbers aren't nice - you can make them into parameters of some function) - but does the trick. From here, minor optimizations are possible (but not as readable, IOHO)
Hope This Helps,
TG
I got a weeknumber from a jquery datepicker, when a user selects a date. But now I want to get all the days within that week.
I could add a click event that loops through all the td's of the tr the selected date is in and graps it's value but I'm looking for a more reliable way.
So my question is, given a certain date and a weeknumber (iso 8601 formatted), how can you derive the other dates within that week with javascript?
You can solve it by subtracting the selected date day (getDate()), with the day of the week (getDay()). This way you have the first day of the week. Then you can use a for loop till 7, to get all the other days. You don't need the weeknumber.
var selected_date = $(this).datepicker('getDate'); //the date the user has clicked
var first_day_of_the_week = new Date(selected_date.getFullYear(),selected_date.getMonth(),selected_date.getDate() - selected_date.getDay() + 1);
var days = [];
for(var i = 0; i < 7; i++){
var day = new Date(first_day_of_the_week.getFullYear(),
first_day_of_the_week.getMonth(),
first_day_of_the_week.getDate() + i);
days.push(day);
}
console.log(days);
There’s a JavaScript implementation of a getWeek function here:
http://www.meanfreepath.com/support/getting_iso_week.html
You could run that on dates seven days either side of your date, and keep the dates for which the week number is the same.