Reputation: 659
If I am getting a date (without time, 'yyyy:mm:dd') as a string from the server ("2022-06-01"), the browser is showing 05/31/2022 when using new Date("06-01-2022").toLocaleDateString()
. But if I remove the toLocaleDateString it's displaying as Wed Jun 01 2022 00:00:00 GMT-0400 (Eastern Daylight Time)
.
I want it to display it as it is in the payload, "06-01-2022", not in the browser's timezone. How do you create a Javascript date based on a string like "06-01-2022" and have it ignore the browser's timezone and display it as a literal "06-01-2022"? I haven't run into this situation before.
Upvotes: 0
Views: 82
Reputation: 118
First make sure you are absolutely clear what timezone the server value is for. The following answer assumes the server provides UTC (always a good idea when sending date and time over global Internet).
Proposed solution A:
Proposed solution B:
Upvotes: 0
Reputation: 128
Something like this should work, since toLocalDateString returns a date you have to recreate the date to then get the format you need.
const = getFormattedDate = (date) => {
date = new Date(date)
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return month + '-' + day + '-' + year;
}
Upvotes: 1