When writing software, it’s sometimes necessary to determine the value of a date which unfortunately uses only two digits to represent the year. Usually, it’s assumed that the year is somewhere in a specific 100-year range in order to use a cut-off date to decide whether the year is in the 1900’s or the 2000’s.
For example, from a stack overflow answer:
year4 = if year < cutoff "20" + year else "19" + year [/ruby] For example, 30 could be used as the cutoff value. Obviously, this assumes that you will never encounter the value "30" and need to interpret it as "2030" instead of "1930". If, on the other hand, you have another date available which is likely to be quite close to the date with the two-digit year (a reference date), it is possible to choose the century such that the date is closest to the reference date. The following code accomplishes the nearly the same task by determining the century of a two-digit year based on proximity to a reference year (not a date). [ruby] # Given a two-digit year, this method determines the absolute year (ie. the century) based on # proximity to a reference year. def interpret_two_digit_year(ref_year, two_digit_year) unless (0..99).include?(two_digit_year) raise "Invalid argument: year must be in range 0..99, year was #{two_digit_year}" end ref_nearest_century = ref_year.round(-2) ref_century_offset = ref_nearest_century - ref_year year_offset_from_ref = (((two_digit_year + ref_century_offset) + 50) % 100) - 50 ref_year + year_offset_from_ref end [/ruby] The approach is as follows:
- Translate the year into a new coordinate system where it is relative to the first year of the century nearest the reference year, instead of being relative to 0. The year will thereby be in the range (-50..149), relative to the reference year.
- Next, we will map the year to the range -50..50 relative to the reference year by first translating by +50 to bring the range to 0..199, modding by 100 to wrap the 100..199 back into the 0..100 range, and then reverting the initial translation by subtracting 50 to bring the range to the desired -50..50 range
- Lastly, add the resulting offset to the reference year to obtain the final result.
While the best approach is to cease using two-digit years entirely, this approach given above may be helpful in situations where two-digit years are unavoidable, and other nearby dates are available.