1.eval方法转换方法,—推荐使用这种方法

<script type="text/javascript">
//字符串转日期格式,strDate要转为日期格式的字符串
function getDate(strDate){
  var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/, 
   function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');
  return date;
}
//测试
alert(getDate("2012-05-09"));
</script>

2.第二种方法 是使用拆分数组的方式。不建议这样使用,因为这样日期格式不灵活
方法如下

<script type="text/javascript"> 
//字符串转日期格式,strDate要转为日期格式的字符串 
function getDate(strDate) { 
  var st = strDate; 
  var a = st.split(" "); 
  var b = a[0].split("-"); 
  var c = a[1].split(":"); 
  var date = new Date(b[0], b[1], b[2], c[0], c[1], c[2]);
  return date; 
} 
//测试 
alert(getDate("2012-9-20 19:46:18")); 
</script>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐