Can't get my current time using new Date()

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)

Maybe your timezone is wrong.
Try console.log(Date()); to see if it’s correct.

Indeed, it’s showing the Coordinated Universal Time. Why is that?

I suppose you maybe should try changing the time of your system to the local time zone.

The time zone on my computer is Pacific. I still don’t understand why the method is showing the wrong time.

And what does today.toString() show?


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)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.