0

I have a textbox with a date in the format of: 2016.March.23

On the same page I need to pull this date into a javascript Date variable but when I try something like var date = new Date("2016.March.23"); I get invalid date format.

How can I convert this date format to a JS date variable?

2 Answers 2

3

Date constructor takes one of these formats only.

var today = new Date();
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);

You need parse this date using this method.

console.log( parseDate("2016.March.23" ) );
function parseDate(str)
{
  var monthArr = ["January","Febuary","March","April","May","June","July","August","September","October","November","December"];
  var dateItems = str.split(".");
  return new Date( dateItems[0], monthArr.indexOf(dateItems[1]), dateItems[2]  );
}
Sign up to request clarification or add additional context in comments.

5 Comments

I get this error 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'split'
@sd_dracula what argument did you passed to this parseDate method?
A Date hence the error. stirng works just fine. Also, how can I add a few days to the date and then convert it back to the original format?
For converting back to original format you need to get specific values (like year month date) and concatenate them. You can add days by doing date.setDate( date.getDate() + 5)
That is what I was thinking, but how to get the getMonth() into the format of "March" as it oply returns a number.
-1

Try using your text date in standard ISO format:

new Date('2016-03-23');

That should work.

1 Comment

Ok, then convert it to the one you can use.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.