简体   繁体   English

将格式为YYYYMMDD的JavaScript字符串中的日期转换为JavaScript日期的最佳方法是什么?

[英]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. 什么是将日期从格式为YYYYMMDD的JavaScript字符串转换为JavaScript日期格式的最佳方法。

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

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. 请注意,提供给日期构造函数的月份是实际月份数 - 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 ). 编辑:好的,你的日期部分提取存在一些问题 - substring可能是javascript的子sub,substr,substring方法( sub,substr,substring )中最尴尬的。 And after testing I stand by the month value having to be 1 less than the actual number. 经过测试,我认为月份值必须比实际数字少1。 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. 创建隐藏的div标签并将日期设置为属性。 then retrieve the attribute and use the sub string method to get something like Mar 01. 然后检索属性并使用子字符串方法获得类似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 看看我的操作系统:hypertos(dot)webege(dot)com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM