I need to get the number of milliseconds between now and any fixed time in the future.
This is an example of exactly what I need:
- Get the number of milliseconds between now and the next 6am
- Get the number of milliseconds between now and the next 12pm
- Get the number of milliseconds between now and the next 9pm
Please how can I achieve this using momentjs or just using vanilla Javascript date?
Thank you.
CodePudding user response:
Here is an example of getting the ms between two date objects.
Please note converting the .valueAsDate
into a date object is not nessacary because the value is a Date obj by default.
Date objs are "the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC"
const $ = str => document.querySelector(str);
$("button").addEventListener("click", () => {
const date1 = new Date($("#d1").valueAsDate);
const date2 = new Date($("#d2").valueAsDate);
const msDiff = Math.abs(date1 - date2);
$("#ms").textContent = msDiff;
$("#day").textContent = msDiff / 1000 / 60 / 60 / 24;
});
<input type="date" id="d1">
<input type="date" id="d2">
<button>diff</button>
<p id="ms"></p>
<p id="day"></p>
CodePudding user response:
JavaScript's Date API can get the job done pretty easily.
You'll need to:
Get the current hour and minute (achieved with the
Date()
constructor and thegetHours()
andgetMinutes()
methods)Check whether the occurrence of the next particular hour is today or not. This is done by checking whether the current hour is greater than that particular hour. If it is, we know that the next occurence of this hour is tomorrow. Otherwise, check whether the minutes is 0. If it is, that particular hour is now. Otherwise, it is on the next day. This all is greatly simplified with the use of a ternary operator.
Calculate the difference by simply subtracting the future Date object by the present Date object.
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
var next6AM;
var next12PM;
var next9PM;
next6AM = new Date(now.getFullYear(), now.getMonth(), now.getDate() (hours > 5 || hours == 5 && minutes != 0 ? 1 : 0), 5);
next12PM = new Date(now.getFullYear(), now.getMonth(), now.getDate() (hours > 11 || hours == 11 && minutes != 0 ? 1 : 0), 12);
next9PM = new Date(now.getFullYear(), now.getMonth(), now.getDate() (hours > 20 || hours == 20 && inutes != 0 ? 1 : 0), 20);
const next6AMdiff = next6AM - now;
const next12PMdiff = next12PM - now;
const next9PMdiff = next9PM - now;
console.log('Milliseconds until next 6AM:', next6AMdiff)
console.log('Milliseconds until next 12PM:', next12PMdiff)
console.log('Milliseconds until next 9PM:', next9PMdiff)