最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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);      

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);      
Share Improve this question edited Nov 29, 2011 at 23:42 Jonathan Leffler 756k145 gold badges951 silver badges1.3k bronze badges asked Sep 30, 2010 at 15:13 robertrobert 6253 gold badges12 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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

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)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论