Get the next day and hour appearance in javascript

I am trying to implement a countdown timer to a specific point in time in the future. This point in time is always on the same day of the week and hour and is based on UTC time.

I am trying to write a general function that sets the day of the week and hour, it will return a date object that will represent these criteria in the future.

Examples:

getNextOccuranceOfUTCDayAndHour(1, 7);

Get your next appearance at 7am on Monday. If today is Monday, 5/25/2015 @ midnight UTC, then this function should return a Date object representing Monday 6/1/2015 7:00 UTC.

getNextOccuranceOfUTCDayAndHour(3, 13);

Get your next appearance at 13:00 on Wednesday. If today is Tuesday, 5/26/2015 @ midnight UTC, then this function should return a Date object representing Wednesday 27/05/2015 13:00 UTC.

I tried to write a function for this, and I included this snippet below, but it only works for some dates and not for others. This is incredibly unreliable. I would prefer not to use Moment.js.

 function getNextOccuranceOfUTCDayAndHour(day, hour) { d = new Date(); d.setDate(d.getUTCDate() + (7 + day - d.getUTCDay()) % 7) d.setUTCHours(hour, 0, 0, 0); return d; } function format_seconds(t) { var d = Math.floor(t / 86400); var h = Math.floor(t % 86400 / 3600); var m = Math.floor(t % 3600 / 60); var s = Math.floor(t % 3600 % 60); return ((d > 0 ? d + " d. " : "") + (h > 0 ? h + " h. " : "") + (m > 0 ? m + " m. " : "") + s + " s."); } function update() { var next_occurance = getNextOccuranceOfUTCDayAndHour(1, 7); $('#next_occurance').text(next_occurance); var ms = next_occurance - new Date(); $('#countdown').text(format_seconds(Math.floor(ms / 1000))); } $(function() { update(); setInterval(update, 1000); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="next_occurance">Next Occurance</p> <p id="countdown">Countdown</p> 

Edit: Some examples of expected and returned values. Jsfiddle

+6
source share
1 answer

The problem in the source code was to use d.setDate(); instead of d.setUTCDate(); . In addition, if the current day was on the same day of the week as the target day, the result was incorrect. Just adding an if statement to test this case fixes this problem.

Updated JSFiddle: https://jsfiddle.net/2j49q0ak/1

0
source

Source: https://habr.com/ru/post/987894/


All Articles