A-A+
javascript replace和split 实现日期自动拆分年月日
因为工作需我们需在用户输入学2012年5月或者2012-05,我们要取出2012给下text而月份要给5这个数了,下面我结合了javascript replace和split 解决这个问题。
html页面,代码如下:
- <input onchange="setdate(this.value);" type="text" id="sell_time" size="15" maxlength="10" />
- <input type="text" id="sell_time_year" size="10" />
- <input type="text" id="sell_time_month" size="10" />
javascript代码如下:
- function setdate( value )
- {
- if( value == "" )
- {
- alert('请选择开盘日期!');
- }
- else
- {
- var value = value.replace('年','-');
- var value = value.replace('月','-');
- var datearray = value.split('-');
- if( datearray[1]<=12 )
- {
- document.getElementById("sell_time_year").value =datearray[0];
- document.getElementById("sell_time_month").value =datearray[1].replace('0','');
- }
- else
- {
- alert('日期格式不正确,标准格式为:2012-01-01 或 2012年1月1日');
- }
- }
- }