I want to format my date with toIsoString function but the function returns -1 day how to fix it? the event.value format is Tue Apr 19 2022 00:00:00 GMT 0400 (Armenia Standard Time)
console.log(new Date(event.value).toISOString().slice(0,10))
in the console, I'm getting this one 2022-04-18
how you can see the result was -1 day
startDateChange(event: any): void{
this.firstDayOfMonth = event;
console.log(new Date(event.value).toISOString().slice(0, 10));
}
CodePudding user response:
This is because of your timezone settings. The toISOString
is always returning 0000
while you work with 0400
in your timezone. This essentially withdraws 4 hours resulting in the day before, 20:00 hours.
You could try to fix this by setting the timezone offset to 0 by adding a Z to the date as shown in the second example.
The third example is a safe way to do it but you need to prefix the 0 if you need that.
Another alternative would be to use a date-library like Moment.js, although moment is deprecated (I don't know for sure what the best alternative would be, that's up to you).
// Your example (this might work for some people that are in the 0000 timezone)
console.log(new Date('2021-03-03T00:00:00').toISOString().slice(0,10));
// Second example
console.log(new Date('2021-03-03T00:00:00z').toISOString().slice(0,10));
// Third example
const date = new Date('2021-03-03T00:00:00');
const year = date.getFullYear();
const month = date.getMonth() 1;
const day = date.getDate();
console.log(`${year}-${month}-${day}`);
CodePudding user response:
You can use https://day.js.org/
Code:
const dateString = 'Tue Apr 19 2022 00:00:00 GMT 0400 (Armenia Standard Time)'
const date1 = dayjs(dateString).format('YYYY-MM-DD')
console.log(date1)
const date2 = dayjs(dateString).format('YYYY-M-D')
console.log(date2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.0/dayjs.min.js"></script>