A-A+

javascript replace和split 实现日期自动拆分年月日

2016年01月18日 前端设计 暂无评论 阅读 5 views 次

因为工作需我们需在用户输入学2012年5月或者2012-05,我们要取出2012给下text而月份要给5这个数了,下面我结合了javascript replace和split 解决这个问题。

html页面,代码如下:

  1. <input  onchange="setdate(this.value);"   type="text" id="sell_time" size="15" maxlength="10"     />  
  2. <input type="text"  id="sell_time_year" size="10" />  
  3. <input type="text"  id="sell_time_month" size="10" />  

javascript代码如下:

  1. function setdate( value )  
  2. {  
  3.  if( value == "" )  
  4.  {  
  5.   alert('请选择开盘日期!');    
  6.  }  
  7.  else  
  8.  {  
  9.   var value = value.replace('年','-');  
  10.   var value = value.replace('月','-');  
  11.   var datearray = value.split('-');    
  12.     
  13.   if( datearray[1]<=12 )  
  14.   {  
  15.    document.getElementById("sell_time_year").value =datearray[0];  
  16.    document.getElementById("sell_time_month").value =datearray[1].replace('0','');  
  17.   }  
  18.   else  
  19.   {  
  20.    alert('日期格式不正确,标准格式为:2012-01-01 或 2012年1月1日');  
  21.   }  
  22.  }  
  23. }  
标签:

给我留言