理想情况下,会有一个函数通过一致的“有线格式”获取日期
有一个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 );
编辑:
以上内容恰好适用于 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 ) )
}
}
}
}() );