In my country, today is 12/15/2022
, I'm from Asia which is gmt 8.
Basically I want my date to be 2022-12-15T00:00:00.000Z
instead of showing 2022-12-14T16:00:00.000Z.
here is the code:
const today = new Date().toLocaleDateString();
console.log(new Date(today));
But I really want it to be exact like this
2022-12-15T00:00:00.000Z
is it possible without using logic "add 8 hours"?
CodePudding user response:
One way is to run your code in UTC zone so that you don't accidentally create dates in different time zones. You can set TZ='UTC'
environment variable for this.
Otherwise you can create the date like this.
const today = new Date().setUTCHours(0, 0, 0, 0); // note 'today' is a number now
> console.log(new Date(today))
2022-12-15T00:00:00.000Z
CodePudding user response:
you can force your time zone like this
console.log(new Date(new Date().toLocaleDateString('en', {timeZone: 'Asia/Hong_Kong'})))
Edit: changed toLocaleString to toLocaleDateString this should meet your needs now
CodePudding user response:
You can first convert the date to a local date string, then parse the year, month and day from it to construct the local ISO zero date string:
const localDate = new Date().toLocaleDateString('en', {timeZone: 'Asia/Hong_Kong'});
console.log('localDate:', localDate);
let m = localDate.match(/(\d )\/(\d )\/(\d )/);
let localZero = m[3] '-' m[1] '-' m[2] 'T00:00:00.000Z';
console.log('localZero:', localZero);
Output:
localDate: 12/15/2022
localZero: 2022-12-15T00:00:00.000Z