How can I find time difference in seconds between two different timezones.
I want to use moment for this -
My start time is something like- 2022-09-04T07:29:39Z[UTC] and end time will be the current time in my frontend.
My code =
var now = new Date().getTime();
var then = "2022-03-04T07:29:39Z[UTC]";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss")); //NAN
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");
console.log("Time Difference =",s);
I need help in this, currently I am getting ms as NAN how can I correct it!
d.format is not a function exposed by momentjs instead of that you should write like below
var now = new Date().getTime();
var then = "2022-03-04T07:29:39Z[UTC]";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = moment(d).format('hh:mm:ss')
console.log("Time Difference =",s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
This type of calculation can easily be done with Vanilla JavaScript:
const now = new Date().getTime(),
then = new Date("2022-03-04T07:29:39Z"),
tsec= Math.round((now-then)/1000),
sec=tsec%60, tmin=(tsec-sec)/60,
min=tmin%60, th=(tmin-min)/60,
h=th%60, d=(th-h)/24;
console.log(`Time Difference = ${d}d ${h}h ${min}m ${sec}s`);