13

How to convert date string to Date object ?

2011-09-19T19:49:21+04:00
Bdfy
  • 23,141
  • 55
  • 131
  • 179
  • 2
    Where this date string is coming from? If from server, your only safe way is to do it manually as each country might have different format for date and time and you can't know that for sure. – Shadow The GPT Wizard Oct 16 '11 at 14:50
  • 2
    Check this post: http://stackoverflow.com/questions/476105/how-can-i-convert-string-to-datetime-with-format-specification-in-javascript – Annie Lagang Oct 16 '11 at 14:55
  • 1
    how exactly is this related to `jquery` , because you have added that tag ? – tereško Oct 16 '11 at 15:20

3 Answers3

26

The best way to do this is using new Date()

Example:

var stringDate = '2011-09-19T19:49:21+04:00'
var date = new Date(stringDate) // Mon Sep 19 2011 08:49:21 GMT-0700 (PDT)
Verdi Erel Ergün
  • 1,021
  • 2
  • 12
  • 20
12

Use jquery ui date parser.

http://docs.jquery.com/UI/Datepicker/parseDate

This is the best function for parsing dates out of strings that I've had the pleasure to work with in js. And as you added the tag jquery it's probably the best solution for you.

fmsf
  • 36,317
  • 49
  • 147
  • 195
  • 2
    Does Datepicker support times? i.e. the 19:49:21+04:00 part?? – Adam Apr 12 '13 at 08:54
  • 1
    this link is may also be useful https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse – zabusa Aug 17 '15 at 10:47
2

I just wrote a javascript function that works for any date input field. I'm using jquery date picker and it works well with that.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to extract characters from the string.</p>

<button onclick="myFunction()">Try it</button>

<p id="enddate"></p>
<p id="startDate"></p>

<script>
  function myFunction() {
//var str = document.getElementById("start_date).value;
// var end = document.getElementById("end_date).value;

  var str = "2014-11-26";
  var end = "2014-11-22";


//first four strings (year) - starting from zero (first parameter), ends at 4th character (second parameter). It excludes the last character.
var year = str.substring(0,4);
var month = str.substring(5,7);//first two characters since 5th. It excludes the 7th character.
var date = str.substring(8,10);//first two character since 8th char. It excludes the 10th character.


var endYear = end.substring(0,4);
var endMonth = end.substring(5,7);
var endDate = end.substring(8,10);

var startDate = new Date(year, month-1, date);
var endDate = new Date(endYear, endMonth-1, endDate);

document.getElementById("enddate").HTML=endDate;
document.getElementById("startDate").HTML=startDate;


if (startDate > endDate) {
  alert('start date should be less than end date');
  return false;

} else {

 alert('date is ok..');
 return true;
}



}
 </script>

 </body>
 </html>

hope it helps. Happy coding :)

user2182143
  • 992
  • 9
  • 10