理想情况下,会有一个函数通过一致的“有线格式”获取日期
有一个input.valueAsDate
方法返回一个Date
反映输入当前值的对象。
根据实验(编辑:2013年12月20日使用Chrome和Opera桌面版本),看来显示的日期输入的值遵循与返回的格式相同的格式new Date().toLocaleDateString()
,至少在 Chrome 中是这样。
前端有 3 种正在执行的日期表示:
- JavaScript 日期对象
- 输入属性和表面值的 ISO 日期字符串
- 由输入向用户表示的日期字符串。
要从其中任何一个获取其中任何一个:
// From Javascript `Date` object to input value:
new Date().toISOString().substr( 0, 10 );
// From Javascript `Date` object to input display:
new Date().toLocaleDateString();
// From input value to Javascript `Date`:
input.valueAsDate;
// From input value to input display (step 3, then step 2):
input.valueAsDate.toLocaleDateString();
// From input display to Javascript `Date` object:
new Date( input.valueAsDate );
// From input display to input value (step 5, then step 1):
new Date( input.valueAsDate ).toISOString().substr( 0, 10 );
EDIT:
以上恰好适用于 Chrome。 Desktop Safari 5.1.7 以 ISO 格式显示时间,这意味着您输入的就是用户看到的。 iOS Safari 显示一个下拉菜单,其中包含月份名称缩写,格式如下dd mmm yyyy
。所以好像没有标准。
这里有一个小函数,可以为您提供仅适用于桌面 Chrome 和 Opera 的正确转换:
var dateInput = ( function inputDateClosure(){
// Type checking
function getType( x ){
return Object.prototype.toString.call( x );
}
function isDate( x ){
return getType( x ) === '[object Date]';
}
function isInput( x ){
return getType( x ) === '[object HTMLInputElement]' || '[object Object]' && Object.prototype.hasOwnProperty.call( x, 'value' );
}
function isString( x ){
return getType( x ) === '[object String]';
}
function fromDateToValue( x ){
return x.toISOString().substr( 0, 10 );
}
function fromDateToString( x ){
return x.toLocaleDateString();
}
function fromInputToDate( x ){
return x.valueAsDate;
}
function fromStringToDate( x ){
return new Date( x.valueAsDate );
}
return function( x ){
if( isDate( x ) ){
return {
asDate : x,
asValue : fromDateToValue( x ),
asString : fromDateToString( x )
}
}
else if( isString( x ) ){
return {
asDate : fromStringToDate( x ),
asValue : fromDateToValue( fromStringToDate( x ) ),
asString : fromStringToDate( fromDateToString( x ) )
}
}
else if( isInput( x ) ){
return {
asDate : fromInputToDate( x ),
asValue : fromDateToValue( fromInputToDate( x ) ),
asString : fromDateToString( fromInputToDate( x ) )
}
}
}
}() );