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?

1
  • 1
    You date text should in either format described here Commented Apr 18, 2015 at 10:03

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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

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.