JavaScript date variable is returning incorrect dates for string input

Tags: ,



I am receiving a string containing a datetime from a web service that is formatted as dd/MMM/yyyy hh:mm:ss it is not possible to change the web service output to match this JavaScript applications needs.

For the sake of simplicity I am replacing the web service data with hardcoded Strings that have their values below.

// The raw input from the web service
var dateOne = new Date("04/Mar/2020 08:00:00");// Invalid Date {}

// After .replace to make it valid
var dateTwo = new Date("04-Mar-2020 08:00:00");// Sat Mar 04 2000 10:00:00

dateOne is invalid (Used to be valid but recently has been proving difficult)

dateTwo is valid but incorrect (Time change from 8 to 10 is correct based on time zone but my time zone is not 20 years in the past)

If anyone could point me in the right direction that would be much appreciated. Thank you in advance.

Answer

Unfortunatley, intialising a date from a date string, the way you are doing it, is strongly discouraged

Note: Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies.

  • Support for RFC 2822 format strings is by convention only.
  • Support for ISO 8601 formats differs in that date-only strings (e.g. “1970-01-01”) are treated as UTC, not local.

However, you can explicitly parse the date string using momentJS

const dateString = '04/Mar/2020 08:00:00';
const date = moment(dateString, 'DD/MMM/YYYY HH:mm:ss');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


Source: stackoverflow