Get Seconds from midnight UTC
Get Seconds from midnight UTC
I simply need the number of seconds from the midnight of the present day.
It's a labyrinth of JS Date
methods I can't untangle from.
Date
I already searched for an off-the-shelf snippet. I tried this but it returns local time, not UTC:
let date = new Date(),
d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(),
date.getUTCSeconds())),
e = new Date(d),
secsSinceMidnight = Math.floor((e - d.setUTCHours(0,0,0,0)) / 1000);
Here's my latest attempt (post updated).
– davide
Sep 15 '18 at 1:25
Running that in node works for me. Currently returning ~5500, which is about an hour and a half (it's currently ~01:30 UTC).
– jhpratt
Sep 15 '18 at 1:33
It yields 16466 on my computer now. Fine, I incorrectly assumed this KVM instance had an adjusted hw clock
– davide
Sep 15 '18 at 1:37
1 Answer
1
I think you had the right idea, but got lost in the implementation. Your assignment to d is just a very long winded way of creating a copy of date that is equivalent to the assignment to e.
To get "seconds from UTC midnight", create a Date for now and subtract it from a copy that has the UTC hours set to 00:00:00.000.
function secsSinceUTCMidnight()
var d = new Date();
var c = new Date(+d);
return (d - c.setUTCHours(0,0,0,0)) / 1000;
console.log('Seconds since UTC midnight: ' +
secsSinceUTCMidnight().toLocaleString() + 'n' + new Date().toISOString());
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Please post your attempts.
– jhpratt
Sep 15 '18 at 1:23