lost_in_the_source
lost_in_the_source

Reputation: 11237

Convert 2 digit year to 4 digit year

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?

Upvotes: 3

Views: 6506

Answers (5)

thydzik
thydzik

Reputation: 165

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

Upvotes: 0

mpen
mpen

Reputation: 282865

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.

Upvotes: 3

return true
return true

Reputation: 7916

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;
}

Upvotes: 5

Nicolas Charvoz
Nicolas Charvoz

Reputation: 1509

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);
}

Upvotes: 0

n0p
n0p

Reputation: 3496

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.

Upvotes: 1

Related Questions