中国开发网: 论坛: 爱情故事: 贴子 138718
zhong
stringToDate
下面是一个例子。
前面的都是对输入字串的处理,看不懂也没关系,你也可以自己分离用户输入的字串成年,月,日的值,
或者也不用分离,只要你设三个输入框,分别对应年,月,日,让用户单独输入,你直接使用就行了。
最后的结果是通过这个转换的 return new Date(year, month, day);
所以你只要把分离出来的年,月,日作为参数 new一个DATE字段就变成日期型了。

var bbDateFormat = "yyyy/MM/dd";

function stringToDate(text, format)
{
if (text == null || text.length == 0)
{
return null;
}

if (!format)
{
format = bbDateFormat;
}

var yearIndex = format.search(/yyyy/i);
var year;
if (yearIndex >= 0)
{
year = text.substring(yearIndex, yearIndex + 4);
}
else
{
yearIndex = format.search(/yy/i);
shortYear = parseInt(text.substring(yearIndex, yearIndex + 2));
var currentYear = new Date().getFullYear();
var lowYear = currentYear - 40;
var highYear = currentYear + 59;
if (shortYear < highYear % 100)
{
// this is in the high century
year = shortYear + Math.floor(highYear / 100) * 100;
}
else
{
year = shortYear + Math.floor(lowYear / 100) * 100;
}
year = parseInt(year);
}

var monthIndex = format.search(/mm/i);
var dayIndex = format.search(/dd/i);

var month = text.substring(monthIndex, monthIndex + 2) - 1;
var day = text.substring(dayIndex, dayIndex + 2);

return new Date(year, month, day);
}

function dateToString(date, format)
{
if (date == null)
{
return null;
}

var result = ((format) ? format : bbDateFormat);
result = result.replace(/yyyy/i, date.getFullYear());
result = result.replace(/yy/i, date.getFullYear().toString().substring(2));
result = result.replace(/mm/i, bbGetDD(date.getMonth() + 1));
result = result.replace(/m/i, date.getMonth() + 1);
result = result.replace(/dd/i, bbGetDD(date.getDate()));
result = result.replace(/d/i, date.getDate());

return result;
}

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录