robert
robert

Reputation: 625

What is the best way to convert date from JavaScript string in format YYYYMMDD to JavaScript date?

What is best way to convert date from JavaScript string in format YYYYMMDD to JavaScript date format.

var from_date = document.getElementById('from_date').value;             
var YYYY = from_date.substring(0,4);
var MM = from_date.substring(4,7);
var DD = from_date.substring(7,8);      

Upvotes: 1

Views: 9703

Answers (2)

Daniel
Daniel

Reputation: 1

It's easy, I struggled with the same question but came up with an easier way. Create a hidden div tag and set the date into an attribute. then retrieve the attribute and use the sub string method to get something like Mar 01.

     <div id="test" style="display:none;" date=""></div>
     <script type="text/javascript">
     var date = new Date();
     document.getElementById('test').setAttribute('date',date);
     var getdate = document.getElementById('test').getAttribute('date');
     var newdate = getdate.substr(4,7);
     alert(newdate);
     </script>

That's all thanks! check out my operating system: hypertos(dot)webege(dot)com

Upvotes: 0

lincolnk
lincolnk

Reputation: 11238

var myDate = new Date( parseInt(YYYY,10), parseInt(MM,10)-1, parseInt(DD,10) );

note that the month provided to the date constructor is actual month number - 1.

edits: ok, there are some issues with your date part extraction- substring is probably the most awkward of javascript's sub-stringing methods (sub,substr,substring). And after testing I stand by the month value having to be 1 less than the actual number. Here is a fixed sample.

var from_date = "20101127"; //document.getElementById('from_date').value; 
var YYYY = from_date.substring(0, 4);
var MM = from_date.substring(4, 6);
var DD = from_date.substring(6);
var myDate = new Date(parseInt(YYYY, 10), parseInt(MM, 10) - 1, parseInt(DD, 10)); 
alert(myDate); // should be november 27th 2010

Upvotes: 4

Related Questions