我只是想知道是否可以将日期字符串 YYMMDD
转换为 YYYY-MM-DD
,例如 990102
-> 1999-01-02
在 JavaScript 中?
从评论中编辑:
如果提供日期 200102
,则需要输出 2012-01-02
,而不是 1920-01-02
最佳答案
除非您提供何时使用 2000+ 以及何时使用 1900+ 的条件,否则您不能。基本上YY里少了几千几百的信息。没有明显的方法可以确定 14 是 2014 年还是 1914 年
所以你可以像[1990 - 2089]
这样的窗口.所以如果YY>=90
使用1900+。如果YY<90
使用 2000+ 窗口可以根据您的要求进行调整
我不确定使用什么窗口是否有任何标准。
@Kos说:
There's a POSIX standard: "When a century is not otherwise specified, values in the range [69,99] shall refer to years 1969 to 1999 inclusive, and values in the range [00,68] shall refer to years 2000 to 2068 inclusive"
ECMA-262 (which is probably more appropriate for javascript) says that any year from 0 to 99 should be treated as 1900 to 1999 (§20.3.2.1). But of course implementations can do what they want for formats not covered by the spec. In Safari, 1/1/49 is 2049, 1/1/50 is 1950.
//990102 -> 1999-01-02
//using window [1990-2089]
function convertDate(yymmdd) {
var d = yymmdd; // YYMMDD
var yy = d.substr(0, 2);
var mm = d.substr(2, 2);
var dd = d.substr(4, 2);
var yyyy = (+yy < 90) ? '20' + yy : '19' + yy;
return yyyy + '-' + mm + '-' + dd;
}
console.log(convertDate('900102'))
console.log(convertDate('140102'))
console.log(convertDate('890102'))
关于javascript - 在 JavaScript 中将字符串 YYMMDD 转换为 YYYYMMDD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43866557/