1

I am having the date format dd-MMM-yyyy while getting data from server side. I am doing some validation with it like

 if (new Date("02-MAY-2018").toDateString() == new Date(this.dob).toDateString()) {
   alert("No error");
 }
 else {
   alert("error");
 }   

Here new Date("02-MAY-2018").toDateString() this conversion is working on chrome, but not in IE

Sridhar Paiya
  • 458
  • 2
  • 9
  • 27
  • 1
    I would say that: `The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).` --and -- `parsing of date strings with the Date constructor 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.` - MDN – Matus Dubrava May 03 '18 at 06:37
  • 1
    note: doesn't work in Firefox either – Jaromanda X May 03 '18 at 06:44

2 Answers2

2

If you know the pattern of date string that you are getting will not change then you can write your own parser. This should work across all the browsers.

const date = "02-MAY-2018";

const parseDate = dateStr => {
  const parts = dateStr.split('-');
  const months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
  const day = Number(parts[0]);
  const month = Number(months.indexOf(parts[1].toLowerCase()));
  const year = Number(parts[2]);

  return new Date(year, month, day);
}

console.log(parseDate(date).toDateString());

It is a little bit verbose but it gets the job done.

And then you can simply change your code like this:

if (parseDate("02-MAY-2018").toDateString() == new Date(this.dob).toDateString()) {
  alert("No error");
} else {
  alert("error");
} 

Note that you might need to change the right side of the comparison - new Date(this.dob) to parseDate(this.dob) depending on the structure of this.dob

Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
  • I modified your code and that is working `parseDate(dateStr) { const parts = dateStr.split('-'); const months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']; const day = parts[0]; const month = months.indexOf(parts[1]); const year = parts[2]; const date = new Date(year, month, day); return date; }` – Sridhar Paiya May 03 '18 at 08:44
-2

1) I think the format, you are talking about is dd-MM-yyyy, not dd-MMM-yyyy, right?

2) If yes, then you should understand that Date object, parses it like MM-dd-yyyy.

So you should either change the format, either, replace days with months in your received string.

Sergej
  • 2,030
  • 1
  • 18
  • 28