0

I need to save the current UTC date/time and current date/time of specific timezone (new york). So im thinking to get utc and then convert it to that timezone.

Correct me if im wrong but im doing:

const date = new Date();
const dateUTC = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()));

//current UTC
console.log(dateUTC.toString())
//current New York
console.log(new Date(dateUTC.toLocaleString("en-US", {
  timeZone: "America/New_York"
})).toLocaleString()) //current local new york

// format before saving:

const strDate = dateUTC.getFullYear() + "-" + (dateUTC.getMonth() + 1) + "-" + dateUTC.getDate();
console.log(strDate);
// same with new york, same for time

But the problem is I think is not necessary to create the utc since date.time() is always in utc. Also I dont need my local time or user local time, just UTC and New York. Or should I get local and convert from local? This is my first time converting dates in JS, any answer will be appreciated

RobG
  • 142,382
  • 31
  • 172
  • 209
WillTech
  • 68
  • 6
  • 1
    This has been asked a bazillion times in various different ways. See the dup link for the answer that explains it the best (IMHO). Note that in your code, it's an error to pass the result of `toLocaleString` back into the `Date` constructor. – Matt Johnson-Pint Sep 29 '22 at 01:02
  • 1
    Also, your second line that creates `dateUTC` is almost a no-op. The only thing it is doing is stripping out the milliseconds. The original `date` is *already* in UTC. All `Date` objects are. – Matt Johnson-Pint Sep 29 '22 at 01:03
  • The current UTC date and time is returned by `new Date().toISOString()` regardless of regional settings. It's dependent only on system clock accuracy. To get the date and time in New York you can use `date.toLocaleString('en',{timeZone:'America/New_York'})` with whatever addtiional options you need. – RobG Oct 03 '22 at 04:20

0 Answers0