Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a two digit year to a four digit year

Tags:

string

date

c#

This is a question of best practices. I have a utility that takes in a two digit year as a string and I need to convert it to a four digit year as a string. right now I do

//DOB's format is "MMM (D)D YY" that first digit of the day is not there for numbers 1-9 string tmpYear = rowIn.DOB.Substring(rowIn.DOB.Length - 3, 2); //-3 because it is 0 indexed if (Convert.ToInt16(tmpYear) > 50)     tmpYear = String.Format("19{0}", tmpYear); else     tmpYear = String.Format("20{0}", tmpYear); 

I am sure I am doing it horribly wrong, any pointers?

like image 711
Scott Chamberlain Avatar asked Jan 07 '10 22:01

Scott Chamberlain


People also ask

How do you convert a two digit year to a four digit number in Excel?

The function =TEXT(A2,"dd/mm/yyyy") will display your two-digit years as four-digit years, but this approach adheres to the 1900 versus 2000 assumptions explained in the previous topic.

How do you convert a two digit year to a four digit year in Python?

The correct pattern to use is '%d-%b-%y' here, where %b matches an abbreviated month name.

What is a 4-digit year?

Four Digit Year Format means the format which represents all four digits of the calendar year. The first two digits represent the century and the last two digits represent the year within the century (e.g., the century and year nineteen hundred and ninety-six is represented by "1996").

How do you read 2-digit years?

The default windowing algorithm used is as follows: If a 2-digit year is moved to a 4-digit year, the century (1st 2 digits of the year) are chosen as follows: If the 2-digit year is greater than or equal to 40, the century used is 1900. In other words, 19 becomes the first 2 digits of the 4-digit year.


1 Answers

The .NET framework has a method that does exactly what you want:

int fourDigitYear = CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(twoDigitYear) 

That way you will correctly adhere to current regional settings as defined in Control Panel (or group policy):

Regional settings

like image 82
Vedran Avatar answered Sep 29 '22 11:09

Vedran