const moment = require('moment-timezone');
const one_minute = 60000; // 1000 * 60
const one_hour = 3600000; // 1000 * 60 * 60
const one_day = 86400000; // 1000 * 60 * 60 * 24
const FORMATTERS = {
full: "dddd MMM Do hh:mm:ss:SSSS a z",
short: "hh:mm:ss:SSSS a z",
iso: "YYYY-MM-DD",
}
function now(time, format) {
return moment(time, format).tz("America/New_York");
}
let things_to_do_each_day = [];
let today = now().startOf('day');
async function process_daily_queue(wait_ms, delayFunction) {
today.add(1, 'days');
return Promise.all([
function() {
delayFunction(function() {
process_daily_queue(one_day, setInterval);
}, wait_ms);
},
...things_to_do_each_day
]);
}
module.exports = {
now: now,
today: () => today.clone(),
format: FORMATTERS,
// ISO 8601 ride or die
iso: time => (time || today).format(FORMATTERS.iso),
days_remaining_until: function(other) {
return other.diff(today, "days");
},
add_to_daily_queue: function(thing_to_do_each_day) {
things_to_do_each_day.push(thing_to_do_each_day);
},
start_daily_interval: function() {
const start_of_next_day = today.clone().add(1, 'days');
process_daily_queue(
(start_of_next_day.diff(now(), "seconds") * 1000) + one_minute,
setTimeout
);
},
one_minute,
one_hour,
one_day
};