APW
APW

Reputation: 59

Converting Javascript String to Datetime

I have a text box that is populated from a datepicker in Javascript. The date is stored as 30-Jan-2013. I want to convert this to a date so I can use it in other calculations.

I have tried

var date1 = new Date(document.getElementById('textbox').value)

but this returns Nan

if I drop the new Date part e.g.

var date1 = (document.getElementById('textbox').value

I get the date 30-Jan-2013 I just don't seem to be able to convert this?

Upvotes: 1

Views: 15127

Answers (3)

Joy Acharya
Joy Acharya

Reputation: 680

Hope this will work for your problem

  var date= document.getElementById('textbox').value.split("-");;
  var date1 = new Date(date[2] + " " + date[1]  + " " + date[0]);
  date1 .toLocaleDateString("en-GB");

Upvotes: 0

Vadim Ivanov
Vadim Ivanov

Reputation: 633

I'd like to recommend you a simple, easy to use and fast library [moment.js][1]

moment("30-Jan-2013").format('MMMM Do YYYY, h:mm:ss a');

will return "January 30th 2013, 12:00:00 am"

Upvotes: 0

Kelsey
Kelsey

Reputation: 47766

Looks like Date.parse is not going to work because the format the datepicker is returning.

You might want to look at the following thread for parsing solutions or change your format that the datepicker outputs to one of the supported formats.

How can I convert string to datetime with format specification in JavaScript?

http://blog.dygraphs.com/2012/03/javascript-and-dates-what-mess.html

Useful parse info:

http://msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx

Upvotes: 1

Related Questions