如何将这样格式化为2年的年份转换为四年:
02 -> 2002
87 -> 1987
等...
到目前为止 :
char shortYr[3];
char longYr[5];
scanf("%2s", shortYr);
int shortYrAsInt = atoi(shortYr);
if (shortYrAsInt < 99)
;
如何转换它?在互联网上,我读到了将4位数转换为2位数的问题,这很容易,但另一种方式呢?
答案 0 :(得分:1)
int longYear;
if (shortYrAsInt <= 15) { // this should be the number where you think it stops to be 20xx (like 15 for 2015; for every number after that it will be 19xx)
longYear = shortYrAsInt + 2000;
} else {
longYear = shortYrAsInt + 1900;
}
答案 1 :(得分:0)
这并不是真正的&#34;转换&#34;,更多&#34;解释&#34;你想要实现的目标。
atoi
将字符串表示转换为整数2000
和00
14
1900
否则。答案 2 :(得分:0)
如果您只想使用char:
if (shortYrAsInt < 15) { // The number where it stops being 20xx
sprintf(longYr, "20%s", shortYr);
}
else {
sprintf(longYr, "19%s", shortYr);
}
答案 3 :(得分:0)
我认为这样的事情会很好用(用JS编写):
if(year >= 0 && year < 100) {
const now = new Date();
const fullYear = now.getFullYear();
let shortYear = fullYear % 100;
let m1 = fullYear - shortYear;
let m2 = m1 - 100;
let opt1 = year + m1;
let opt2 = year + m2;
year = Math.abs(fullYear - opt1) < Math.abs(fullYear - opt2) ? opt1 : opt2;
}
即,它会选择接近当年,19XX或20XX的那一个。
答案 4 :(得分:0)
有点令人费解,但这对我有用(python)
num = "99"
year = int(num) + (1-round(int(num)/100))*2000 + round(int(num)/100)*1900