0

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.

6
  • "04/Mar/2020 08:00:00" is of format dd/MMM/yyyy hh:mm:ss not dd/MM/yyyy hh:mm:ss Commented Mar 3, 2020 at 9:24
  • 1
    use momentjs - all the hard work of using dates in javascript has been done already in that library - really, because dates in javascript are a nightmare!! Commented Mar 3, 2020 at 9:24
  • by the way, in my browser the result of the year is MINUS 2020 :p - however new Date("04 Mar 2020 08:00:00"); seems to work (but I wouldn't rely on it) Commented Mar 3, 2020 at 9:25
  • In console new Date("04-Mar-2020 08:00:00") is Wed Mar 04 2020 08:00:00 GMT+0200 (Eastern European Standard Time) and new Date("04/Mar/2020 08:00:00") is Wed Mar 04 2020 08:00:00 GMT+0200 (Eastern European Standard Time) . So, which is actually the problem ? Commented Mar 3, 2020 at 9:27
  • @JaromandaX The spaces also put it in 2000, but why is it unreliable? Commented Mar 3, 2020 at 9:29

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.