Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a year from 4 digit to 2 digit and back again in C#

My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing:

  1. I put a DropDownList of the 4-digit year on the page.
  2. I validate the expiration date in a DateTime field to be sure that the expiration date being passed to the CC processor isn't expired.
  3. I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL.

Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the DateTime object. Or should I just keep processing it as I am?

like image 248
Mike Wills Avatar asked Sep 22 '08 15:09

Mike Wills


People also ask

How to convert 2-digit year to 4-digit year?

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.

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.

How do I get 2-digit year in Excel?

We can just open the Format Cells dialog by pressing Ctrl + 1. After that select the Custom category on the Number tab, and enter one of the codes below in the Type box: yy – to display 2-digit years, as 00-99. yyyy – to display 4-digit years, as 1900-9999.


1 Answers

If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so:

DateTime expirationDate = new DateTime(2008, 1, 31); // random date string lastTwoDigitsOfYear = expirationDate.ToString("yy"); 

Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first.

like image 100
brock.holum Avatar answered Sep 22 '22 04:09

brock.holum