0

I have several dates in this text format:

var date = "March 12th 2015, 8:37:29 pm";

I want to get a date object but I am getting invalid date when creating the date object.

I tried just doing:

var date_o = new Date(date);

No success. Also tried:

  var at = Date.parse(date.replace(/[ap]m$/i, ''));
  if(date.match(/pm$/i) >= 0) {
     at += 12 * 60 * 60 * 1000;
  }
  var date_o = new Date(at);

No success. What would be the correct way?

I think I should tell the date object that will get a string with "format('MMMM Do YYYY, h:mm:ss a')". Is this possible?

Egidi
  • 1,736
  • 8
  • 43
  • 69
  • 1
    You date text should in either format described [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) – hindmost Apr 18 '15 at 10:03

2 Answers2

1

as your wish , use the construction function to get the date :

var date = "March 12th 2015, 8:37:29 pm";

function getDate(str){
    var monthList = ['January','February','March','April','May'
        ,'June','July','August','September','October','November','December'];

    var year = str.slice(11,15);
    var month = monthList.indexOf(str.slice(0,5));
    var day = str.slice(6,8);

    var isAm = str.slice(str.length-2);
    var hour = isAm == 'am' ? +str.slice(17,18) + 12:str.slice(17,18);
    var minute = str.slice(19,21);
    var second = str.slice(22,24);

    var date = new Date(year,month,day,hour,minute,second);

    console.log(date)
    return date;

}

getDate(date)
qianjiahao
  • 399
  • 1
  • 3
  • 10
0

You have a wrong format for date. Just need remove coma, th and AM/PM. So, input text must be like

var date = "March 12 2015 8:37:29";

So after that you can do

var date_o = new Date(date);
console.log(date_o instanceof Date); // ->true
BordiArt
  • 756
  • 8
  • 20