-1

I have a date in this format: '04-Aug-15'.

I want to be able to get a Date object in JS, I'm trying this:

var date = new Date(Date.parse('04-Aug-15', "MM/dd/yyyy"));

But I'm getting invalid date error message.

Any idea how can I fix this?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Laziale
  • 7,965
  • 46
  • 146
  • 262
  • 1
    you're telling the format is `mm/dd/yyyy`, then passing in a date that's `dd-mmm-yy`? what else would you expect if you hand someone a watermelon and tell them "this is an apple"? – Marc B Jul 16 '15 at 15:06
  • @MarcB Thanks Mark, but do you know a way I can give a watermelon and get apple in my case... – Laziale Jul 16 '15 at 15:17
  • `parse('04-aug-15', 'dd-mm-yy')`, or just HOPE that the parser is smart enough to handle `parse('04-aug-15')` as is without the format hint. – Marc B Jul 16 '15 at 15:29
  • 1
    the `mm/dd/yyyy` stuff isn't for what you want the date to look like AFTER wards, it's to tell the system what the date you're passing in looks like RIGHT NOW. – Marc B Jul 16 '15 at 15:29
  • This post helped me http://stackoverflow.com/questions/22058822/parse-string-dd-mmm-yyyy-to-date-object-javascript-without-libraries – Laziale Jul 16 '15 at 15:44

2 Answers2

-1

Just pass new Date the date string, and it'll turn it into a date.

var stringDate='04-Aug-15';
var date=new Date(stringDate);

console.log(date);
depperm
  • 10,606
  • 4
  • 43
  • 67
  • I'm getting the same error message with your approach. – Laziale Jul 16 '15 at 15:16
  • The spec doesn't mandate that the Date constructor should parse dd-mmm-yy format. This works on some browsers and on some browsers it does not. – JJJ Jul 16 '15 at 16:20
-1

Try this to parse your date.

var date = new Date(Date.parse("04-Dec-15"));

You can then print your date by the following function.

window.alert( (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());