0

I have a string formatted like this: January 3 2016. I've tried doing new Date(Date.parse(string)) but I'm getting an invalid date warning. Am I missing something? My end goal is to turn that date into mm/dd/yyyy format, which I should be able to do once I'm in Date format.

Thanks

Nat
  • 890
  • 3
  • 11
  • 23
  • You're not missing something, that's an invalid date. A valid date would be something that conforms to RFC2822 or ISO 8601 – adeneo Jan 03 '16 at 17:55
  • On the other hand, it actually works for me, but that could be browser/locale dependent, `Date.parse` is notoriously unstable when you feed it strange dates. – adeneo Jan 03 '16 at 17:56
  • The spec only defines ISO 8601 (a subset of), but RFC2822 is generally (if not always) accepted. you could easily parse and format the date string yourself without the use of Date or any external library. – Xotic750 Jan 03 '16 at 18:00

3 Answers3

1

For me it's working: Date(Date.parse('January 3 2016'))

Iamisti
  • 1,680
  • 15
  • 30
1

An example of converting/formatting your date string without the use of Date or a library.

var monthLookup = {
  january: '01',
  february: '02',
  march: '03',
  april: '04',
  may: '05',
  june: '06',
  july: '07',
  august: '08',
  september: '09',
  october: '10',
  november: '11',
  december: '12'
};

function customParseAndformat(dateString) {
  var parts = dateString.split(' ');
  parts[0] = monthLookup[parts[0].toLowerCase()];
  parts[1] = parts[1] < 10 ? '0' + parts[1] : parts[1];
  return parts.join('/');
}

var myDateString = 'January 3 2016';
document.getElementById('out').textContent = customParseAndformat(myDateString);
<pre id="out"></pre>

You could use a similar method to parse and the create a Date object from the discrete values, which is far more reliable (cross-environment) than Date.parse. Example

var monthLookup = {
  january: '01',
  february: '02',
  march: '03',
  april: '04',
  may: '05',
  june: '06',
  july: '07',
  august: '08',
  september: '09',
  october: '10',
  november: '11',
  december: '12'
};

function parseAndCreateDate(dateString) {
  var parts = dateString.split(' ');
  parts[0] = monthLookup[parts[0].toLowerCase()] - 1;
  parts[1] = parts[1] < 10 ? '0' + parts[1] : parts[1];
  return new Date(parts[2], parts[0], parts[1]);
}

var myDateString = 'January 3 2016';
document.getElementById('out').textContent = parseAndCreateDate(myDateString).toDateString();
<pre id="out"></pre>

Now, you can format as you wish from the returned Date object, by using its methods.

Where can I find documentation on formatting a date in JavaScript?

Community
  • 1
  • 1
Xotic750
  • 22,914
  • 8
  • 57
  • 79
0

Parsing dates in Javascript is, say, tricky. It's both browser-dependent and culture-dependent, which is a hard challenge to deal with.

Should you target multi browsers and multi countries , I'd recommend you to use moment.js.

roland
  • 7,695
  • 6
  • 46
  • 61