3

How would I convert a 2 digit year formatted like this into four year:

02 -> 2002
87 -> 1987

etc...

What I have so far:

char shortYr[3];
char longYr[5];
scanf("%2s", shortYr);
int shortYrAsInt = atoi(shortYr);

if (shortYrAsInt < 99)
    ;

How do I convert it? On the Internet, I read about converting 4 digit to 2 digit, which is easy, but what about the other way?

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75

5 Answers5

5
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;
}
return true
  • 7,839
  • 2
  • 19
  • 35
3

I think something like this would work well (written in 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;
}

i.e., it will pick whichever is closer to the current year, 19XX or 20XX.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
1

It is not really "converting", more "interpreting" that you are trying to achieve.

  • You will need atoi to convert a string representation to an integer
  • Then make an heuristic to add to your integer:
    • 2000 if the 2 digits are between 00 and 14
    • or 1900 otherwise.
n0p
  • 3,399
  • 2
  • 29
  • 50
0

If you want to use only char :

if (shortYrAsInt < 15) { // The number where it stops being 20xx
    sprintf(longYr, "20%s", shortYr);
} 
else {
    sprintf(longYr, "19%s", shortYr);
}
Nicolas Charvoz
  • 1,509
  • 15
  • 41
0

a bit convoluted, but this worked for me (python)

num = "99"
year = int(num) + (1-round(int(num)/100))*2000 + round(int(num)/100)*1900
thydzik
  • 155
  • 2
  • 11