I'm trying to make my data stay in Brazil's time zone, but every time I try to change it, when I give a console it shows the correct date, but as soon as I send it to my backend the date changes the timezone completely, I just need get today's date, but as there is a time zone, at 9 pm the day changes to the next day, what am I doing wrong? I tried this code here.
let date = new Date();
//this simulates the time after 21:00, just change the 15 to the number of hours needed so that the time is like after 21:00 to test (now is 8 am in Brazil)
date.setHours(date.getHours() 15);
date = date.toISOString().split('T')[0];
$('#date').append(date.toLocaleString("pt-BR"));
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<div id="date">
</div>
CodePudding user response:
Date.toISOString()
will give you the UTC time as an ISO string.
If you want to get your local date as an ISO string, this is easy to do, using the Date.getFullYear()
, Date.getMonth()
and Date.getDate()
values.
We create an array with the [year, month, day] values in it, then use String.padStart()
and String.join()
to create the ISO date.
This will give the correct day of year in the local timezone.
function getIsoDate(date) {
const ymd = [ date.getFullYear(), date.getMonth() 1, date.getDate() ];
return ymd.map(s => (s '').padStart(2, '0')).join('-');
}
console.log(getIsoDate(new Date()));
console.log(getIsoDate(new Date('2022-10-19T22:30:00')));
console.log(getIsoDate(new Date('2022-10-19T00:00:00')));
.as-console-wrapper { max-height: 100% !important; }
A simple hack that will also work is using Date.toLocaleDateString()
with the locale argument set to 'sv', this is because this language displays dates using the ISO format.
function getIsoDate(date) {
return date.toLocaleDateString('sv');
}
console.log(getIsoDate(new Date()));
console.log(getIsoDate(new Date('2022-10-19T21:30:00')));
.as-console-wrapper { max-height: 100% !important; }