I’m in California, right now it is 10:47 AM over here. For some reason new Date() is 7 hours ahead. This code returns 2023-5-19 17:45:56
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
console.log(dateTime)
Also, almost all Javascript environments already support the thing that you’re trying to do manually (albeit will need slight adjustment to match exactly what you want):
const yourDateTime = new Date().toLocaleString('en', {
timeZone: "US/Pacific",
dateStyle: "short",
timeStyle: "medium",
hour12: false,
});
console.log(yourDateTime)
// logs, for me now: "5/22/23, 01:10:18"
const yourDateTimeReformatted = yrDateTime.replace(/(\d+)\/(\d+)\/(\d+), (.+)/, "$1-$2-$3 $4")
console.log(yourDateTimeReformatted)
// logs, for me now: "5-22-23 01:10:18"
Can also output the formatting to parts (array of formatted values) instead of a string, meaning don’t have to use a regex to reformat the output.
This from the functionality in Intl, which contains logic for internationalisation of dates, numbers, currency etc (provides formatting/conversions)