Search code examples
c#datetime2-digit-year

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?


Solution

  • 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.