Home > Net >  Displaying a date string without browser timezone in mm:dd:yyyy with javascript
Displaying a date string without browser timezone in mm:dd:yyyy with javascript

Time:06-10

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.

CodePudding user response:

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;
}

CodePudding user response:

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:

  1. Explicitly pass the server timezone (UTC=Z) to the Date() constructor
  2. Use the toUTCString() method to get an internationally neutral string
  3. Assume that toUTCString has the same exact field lengths in all locales Example: Date("2022-06-01T00:00Z").toUTCString().substring(0,16)

Proposed solution B:

  1. Fudge the date object to think the specified date is local to the users location
  2. Keep the toLocaleDateString() method to get a text that is somewhat similar to the users local formatting rules. Example: Date(2022,6-1,1).toLocaleDateString()
  • Related