To start, utilize the en-CA
locale for the "calculation" process which will yield an output of yyyy-mm-dd hh:mm:ss
, simplifying further manipulation.
Next, include hour12: false
to ensure a 24-hour time format is used.
Now you can proceed with:
const minutesToHHMM = (m) => {
const s = m < 0 ? '-' : '';
m = Math.abs(m);
const mm = (m % 60).toString().padStart(2, 0);
const hh = Math.floor(m / 60);
return `${s}${hh}:${mm}`;
}
const timeZone = 'Australia/Eucla'; // unique timezone choice for consistent minute variations
const date = new Date();
date.setMilliseconds(0); // omit milliseconds for uniformity
const other = new Date(...date
.toLocaleString('en-CA', {
timeZone,
hour12: false,
})
.replaceAll('-',':') // convert yyyy-mm-dd to yyyy:mm:dd
.replaceAll(', ', ':') // insert ':' between date and time
.split(':')
.map((v,i) => v - (i===1))
console.log("other time", other.toLocaleString());
console.log("local time", date.toLocaleString());
console.log("difference", minutesToHHMM((other-date)/60000));
Although my Typescript implementation may not be perfect...
const minutesToHHMM = (m:number) => {
const s = m < 0 ? '-' : '';
m = Math.abs(m);
const mm = (m % 60).toString().padStart(2, "0");
const hh = Math.floor(m / 60);
return `${s}${hh}:${mm}`;
}
const timeZone = 'Australia/Eucla'; // chosen timezone for clarity in minute differences
const date = new Date();
date.setMilliseconds(0); // exclude milliseconds from time comparison
const other = new Date(...(date
.toLocaleString('en-CA', {
timeZone,
hour12: false,
})
.replaceAll('-',':') // convert yyyy-mm-dd to yyyy:mm:dd
.replaceAll(', ', ':') // add ':' between date and time
.split(':')
.map(Number)
.map((v:number, i:number) => v - ((i===1) ? 1 : 0)) as []) // offset month by 1
console.log("other time", other.toLocaleString());
console.log("local time", date.toLocaleString());
console.log("difference", minutesToHHMM((+other - +date)/60000));
Tested this on a TS Playground, appears to function correctly