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
Related
I use Moment.js in a planning application and I observe unexpected behaviors: the software calculates bad hours (+/-1hour spring/winter) when i'm working before the day of the time change (today for sunday) but not when it is the day (the same action on sunday is ok). It seems to anticipate the change when it's not what I want.
I tried to use the extension .utc () with no success.
Thanks for all suggestion.
// return hour from x position
function getHeure(x) {
var dd = moment(heure0, "DD/MM/YYYY HH:mm:ss"); // heure0 contain day/hour of start
var gt = moment(dd).add(parseInt(x / granul),'m') // 'x' is the x point in planning, 'granul' the ratio of min/px
if (dd.date()==27 && dd.month()==9) gt.add(1,'hours') // current workaround for France in 2019...
return gt
}
I think you can follow the same approach as this question.
https://stackoverflow.com/a/11888430/3292394
I have used the solution above and it works perfectly.
Regards,
user3292394
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.
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 need to use JavaScript to display the next event on a recurring weekly basis on a website. Let's say we start an event every 10am every Saturday - I'll need it to display that the next event begins on "Saturday, (Month) (Date) at 10am".
The only thing that I need to be dynamic on the website is the date of the next event (both month and date).
Idea 1: One way I started thinking about it I would need to and have some sort of a starting reference calendar date from where the schedule starts, and then some pattern of n-days to calculate the upcoming dates from that starting point and compare those against todays date, then display the result of the next in the sequence
Idea 2: Instead of using a pattern of N-days to calculate from a hard-coded reference point, what if I coded the day of the week the event occurs and check against that, calculating the date by comparing the days of the week and adding to todays date (would have to account for rollovers at 28/30/31 days and a way to account for which months max out at which number)
Maybe I'm way off-base in my thinking, but any help here would be appreciated. I'm learning JavaScript and coming from an HTML+CSS background using jQuery plugins if that helps frame your answer in a way I'll grasp.
Here is a rough solution that may work. It's just general code that you will need to debug but I think it's a good starting point! Date() is a built-in JavaScript object.
var today = new Date();
//var dd = today.getDate(); *just some sample functions of Date()*
//var mm = today.getMonth()+1; *January is 0!*
if(today.getDay() == 6) alert('it is saturday');
// today.getDate() < 8 *this can be used to check where in the month a day falls
// if you want only first, second, third, etc., Saturday
Please let me know if this helps at all!
You could use rSchedule for this (a javascript recurrence library which I maintain).
Example:
Let's say we start an event every 10am every Saturday
import { Schedule } from '#rschedule/rschedule';
import { StandardDateAdapter } from '#rschedule/standard-date-adapter';
const schedule = new Schedule({
rrules: [{
frequency: 'WEEKLY',
// the hypothetical start datetime of your recurring event
start: new Date(2019, 5, 15, 10),
}],
dateAdapter: StandardDateAdapter,
});
The only thing that I need to be dynamic on the website is the date of the next event (both month and date).
// get standard javascript iterator for occurrences starting after now
const iterator = schedule.occurrences({
start: new Date()
})
// the next date
const nextDate = iterator.next().value;
// or iterate over all future occurrences
for (const date of iterator) {
// do stuff...
}
Here's a timely question. The rules in North America* for time change are:
the first Sunday in November, offset changes to Standard (-1 hour)
the second Sunday in March, offset changes to Daylight (your normal offset from GMT)
Consider a function in JavaScript that takes in a Date parameter, and should determine whether the argument is Standard or Daylight Saving.
The root of the question is:
how would you construct the date of the next time change?
The algorithm/pseudocode currently looks like this:
if argDate == "March"
{
var firstOfMonth = new Date();
firstOfMonth.setFullYear(year,3,1);
//the day of week (0=Sunday, 6 = Saturday)
var firstOfMonthDayOfWeek = firstOfMonth.getDay();
var firstSunday;
if (firstOfMonthDayOfWeek != 0) //Sunday!
{
//need to find a way to determine which date is the second Sunday
}
}
The constraint here is to use the standard JavaScript function, and not scrape any JavaScript engine's parsing of the Date object. This code won't be running in a browser, so those nice solutions wouldn't apply.
**not all places/regions in North America change times.*
if argDate == "March"
{
var firstOfMonth = new Date();
firstOfMonth.setFullYear(year,3,1);
//the day of week (0=Sunday, 6 = Saturday)
var firstOfMonthDayOfWeek = firstOfMonth.getDay();
var daysUntilFirstSunday = (7-firstOfMonthDayOfWeek) % 7;
var firstSunday = firstOfMonth.getDate() + daysUntilFirstSunday;
// first Sunday now holds the desired day of the month
}
1) I expect there could be some other rules in different countries. Some don't have daylight saving at all. So to find the answer in a specific locale you could probably loop throught 365(6) days to find the days where getTimetoneOffset() changes it's value. This should not be a big lag in performance.
2) Then, you can get the specific hour when the time is changes (2 am for US?). Suggest another loop throught 24 hours
PS: Ok, someone has already done the job =). You should test it before using (because I didn't test)
PPS: Your first question was "is daylight applied or not for specific date?". This answer solves the task