I am just wondering is it possible to convert a date string YYMMDD to YYYY-MM-DD, in example 990102 -> 1999-01-02 in JavaScript?
EDIT from a comment :
If date 200102 is provided it need to output 2012-01-02, not 1920-01-02
You cannot unless you provide a condition on when to use 2000+ and when to use 1900+. Its basically less information in YY where the thousands and hundreds are missing. There is no obvious way to determine if 14 is 2014 or 1914
So you can take a window like [1990 - 2089]. So if YY>=90 use 1900+. If YY<90 use 2000+ The window can be adjusted per your requirement
I am not sure if there is any standard on what window to use.
@Kos says:
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 says
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'))
You can use substring method.
var date="990102";
console.log("19"+date.substring(0,2)+"-"+date.substring(2,4)+"-"+date.substring(4,6));
2000+?200102 returns 2012 ?I know this is an old question but here is my solution (in typescript and it worked for me)
private convertDate(yymmdd: string) {
const date: Date = new Date();
const year = date.getFullYear().toString();
const d = yymmdd; // YYMMDD
const yy = d.substr(0, 2);
const mm = d.substr(2, 2);
const dd = d.substr(4, 2);
const yyyy = (+yy < parseInt(year.slice(2, year.length), 10) + 10) ? '20' + yy : '19' + yy;
return `${yyyy}-${mm}-${dd}`;
}
It is an adaptation of the answer above except it ensures the gap remains at an incremental (10) distance from the current year to ensure the sustainability
YYwhere the thousands and hundreds are missing. There is no obvious way to determine if14is2014or1914[1949 - 2050]. So ifYY>=49use1900+. IfYY<50use2000+ The window can be adjusted per your requirementvalueshould be determined per use-case.