In my file HomeComponent.ts (not in template html). I create a new Date and show it in console like this:
var fecha = new Date();
console.log(fecha);
the time in my country now is 16:09 (UTC -3) but the console output shows the date in UTC:
Date 2018-12-20T19:09:32.910Z // the time is 19:09
I need to pare and do some operations with "this new date" and other dates saved in a DB so I need the new Date to be created in my local timezone. How can I create a new Date in my local timezone?
In my file HomeComponent.ts (not in template html). I create a new Date and show it in console like this:
var fecha = new Date();
console.log(fecha);
the time in my country now is 16:09 (UTC -3) but the console output shows the date in UTC:
Date 2018-12-20T19:09:32.910Z // the time is 19:09
I need to pare and do some operations with "this new date" and other dates saved in a DB so I need the new Date to be created in my local timezone. How can I create a new Date in my local timezone?
Share Improve this question edited Oct 24, 2019 at 12:29 ChrisM 5056 silver badges18 bronze badges asked Dec 20, 2018 at 19:15 matQmatQ 6173 gold badges14 silver badges28 bronze badges 2- Possible duplicate of Convert date to another timezone in JavaScript – nircraft Commented Dec 20, 2018 at 19:17
-
1
16:09-03:00 is exactly the same time as 19:09Z. The default toString method will use the local timezone, the console can do what it likes and may use some other method,
console.log(fecha.toString());
will give you local. – RobG Commented Dec 20, 2018 at 20:21
2 Answers
Reset to default 1How can I create a new Date in my local timezone?
Dates don't have a timezone, they are simply an offset from 1970-01-01T00:00:00Z (a time value) so are effectively always UTC. They represent a particular moment in time and can be used to generate a string representing an equivalent date and time in any timezone.
The local offset es from the host system, it's used (if necessary) when creating a date and when working with local date and time values. There are equivalent UTC methods for doing operations that don't consider the local timezone.
The default toString method will generate a timestamp for the host timezone, toISOString will use UTC, toLocaleString can be used to generate a timestamp for any timezone. All will represent the same UTC date and time, just in different timezones.
When paring dates, it's the UTC time value that is pared as it provides a mon factor for all dates.
the time in my country now is 16:09 (utc -3) but the console output show the date in utc
A Date or DateTime is a structure, it does not have a format. If you want to display a formatted date string using the timezone of the browser then call toLocaleString
.
var fecha = new Date();
console.log("As ISO8601 in utc:", fecha);
console.log("As local:", fecha.toLocaleString());