javascript - 在 JavaScript 中将字符串 YYMMDD 转换为 YYYYMMDD

标签 javascript string date

我只是想知道是否可以将日期字符串 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"

@RobG

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/

相关文章:

javascript - 遍历字符串中的元素

java - 将二维数组写入字符串,然后写入 .txt 文件 - Java

javascript - 从 unix 时间戳获取以微秒为单位的 ISOString

c - 根据教授的说法,代码中的段错误应该有效

javascript - 按数据索引值对元素进行排序

javascript - 简单的javascript员工培训调查问卷

javascript - Webpack bundling 如何减少 React 等流行库的重复下载?

angular - TypeScript:无法读取 datepipe.transform 中未定义的属性 'transform'

Java Date getTime函数返回负值

javascript - JavaScript API 问题