Reputation: 918
My brain must be utterly fried, but I cannot for the life of me figure out how to get the current date and time in UTC formatted as a string. No matter what I do, I just get local.
I have the following function which returns the date in the correct format, but it's always local.
let datenow = new Date;
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
const p = new Intl.DateTimeFormat('en', {
year:'numeric',
month:'2-digit',
day:'2-digit',
hour:'2-digit',
minute:'2-digit',
second:'2-digit',
hour12: false
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, {});
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}
Does anyone know what I'm missing?
Upvotes: 2
Views: 22473
Reputation: 79015
A simple way can be getting each UTC unit from the new Date()
object and creating the desired string.
const date = new Date();
const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // Month is 0-based
const day = String(date.getUTCDate()).padStart(2, '0');
const hour = String(date.getUTCHours()).padStart(2, '0');
const minute = String(date.getUTCMinutes()).padStart(2, '0');
const second = String(date.getUTCSeconds()).padStart(2, '0');
const strDate = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
console.log(strDate);
Adding a valuable suggestion by RobG, as sometimes comments get deleted:
Somewhat simpler:
new Date().toLocaleString('en-CA',{timeZone:'UTC', hour12:false}).replace(',','')
.
Upvotes: 1
Reputation: 918
Adding this answer as well that RobG suggested.
let datenow = new Date;
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
const p = new Intl.DateTimeFormat('en', {
year:'numeric',
month:'2-digit',
day:'2-digit',
hour:'2-digit',
minute:'2-digit',
second:'2-digit',
hour12: false,
timeZone:'UTC'
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, {});
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}
Upvotes: 1
Reputation: 1513
We should use in-built toISOString
function to covert it to ISO date format and remove not required data using string manipulation.
let datenow = new Date();
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
return date.toISOString().replace("T"," ").substring(0, 19);
}
Ideally solution should be to use momentjs or dayjs library.
Upvotes: 7