const myTime = Date.now()
console.log(myTime) // 1659622334878
Now when I use it like this
console.log(new Date(myTime).toUTCString())
I get "Thu, 04 Aug 2022 14:12:14 GMT"
How do I format myTime (1659622334878)
so that time of the day doesn't affect the output.
Expected output "Thu, 04 Aug 2022 00:00:00 GMT"
CodePudding user response:
To truncate the date to midnight UTC, try Date.prototype.setUTCHours()
:
const myTime = new Date();
myTime.setUTCHours(0, 0, 0, 0);
console.log(myTime.toUTCString());
CodePudding user response:
It's just a string so slice()
and .concat()
let d = new Date(Date.now()).toUTCString();
console.log(d.slice(0, 17).concat('00:00:00 GMT'));
CodePudding user response:
Given that there are 86,400 seconds in a day (24 × 60 × 60) you can round the result of Date.now()
down to the nearest 86,400,000 milliseconds
let now = Date.now();
let date = new Date(now - (now % 86_400_000));
console.log(date.toUTCString());
No idea why I know off the top of my head that there are 86,400 seconds or 1,440 minutes in 24 hours.
CodePudding user response:
// Created using Date.now(), which returns milliseconds
const myTime = 1659622334878;
// Time constants in milliseconds
const SECOND = 1e3;
const MINUTE = SECOND * 60;
const HOUR = MINUTE * 60;
const DAY = HOUR * 24; // or 8.64e7 or 86_400_000
const myDayAtMidnight = Math.floor(myTime / DAY) * DAY;
// Order of ops: 2 1 3
// 1. Divide by milliseconds in one day to get floating point days
// 2. Remove the remainder
// 3. Multiply by milliseconds in one day to get back to milliseconds
console.log('My day:', new Date(myDayAtMidnight).toUTCString());
console.log('My day with time:', new Date(myTime).toUTCString());
You can, of course, precalculate these dynamically-calculated constants and inline the value for DAY
in your own code, but they're there to provide context for the thought process of solving this problem using the approach of math unit conversion.