Javascript: calculate time between today and a specific subsequent workday
I'm looking for a way to calculate the time in seconds between UTC-7 and next Saturday (regardless of the date the calculation was performed) at a specific UTC-7 (08:00) in Javascript.
I am currently using this code, but I want to replace those giving specific dates with the above calculation:
// Grab the current date
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); currentDate.setHours(currentDate.getHours() - 7);
// Set some date in the future.
var ClashDate = new Date("August 6, 2017 16:40:00");
var BashDate = new Date("August 12, 2017 08:00:00");
// Calculate the difference in seconds between the future and current date
var diffclash = ClashDate.getTime() / 1000 - currentDate.getTime() / 1000;
var diffbash = BashDate.getTime() / 1000 - currentDate.getTime() / 1000;
Can anyone help me?
Yours sincerely Yamper
source to share
For simplicity, you can use MomentJS
to dynamically define dates for next Saturday
and next Saturday
after it.
To specify a date Moment
for this upcoming one Saturday
, you can do so via the API .day(int)
. For example. .day(6)
...
To get epoch
time you can do .unix()
, but there is a catch here. By default, it returns you seconds
as there are epoch
no standard milliseconds.
Example:
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); currentDate.setHours(currentDate.getHours() - 7);
moment().tz("America/New_York").format();
// Set some date in the future.
var ClashDate = moment().day("Saturday").hour(16).minutes(40).seconds(0);
var BashDate = moment().day(13).hour(8).minutes(0).seconds(0);
console.log("Next Saturday date is => " + ClashDate.toString());
console.log("Next Next Saturday date is => " + BashDate.toString());
// Calculate the difference in seconds between the future and current date
var diffclash = ClashDate.unix() - currentDate.getTime() / 1000;
var diffbash = BashDate.unix() - currentDate.getTime() / 1000;
console.log("diffClash => " + diffclash);
console.log("diffBash => " + diffbash);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data.min.js"></script>
Reference:
MomentJS - https://momentjs.com/docs/
source to share
In POJS (one way) you can get the next Saturday at a specific time as follows.
function nextSaturday(date) {
const d = date ? new Date(date) : new Date();
d.setDate(d.getDate() + (6 - d.getDay()) % 7);
return new Date(`${d.toISOString().split('T').shift()}T14:00:00.000Z`);
}
console.log(nextSaturday('2017-08-13'));
console.log(nextSaturday('2017-08-31'));
console.log(nextSaturday());
source to share