Converting a year from 4 digit to 2 digit and back

2019-02-02 02:25发布

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?

15条回答
我命由我不由天
2楼-- · 2019-02-02 02:33

The answer is quite simple:

DateTime Today = DateTime.Today; string zeroBased = Today.ToString("yy-MM-dd");

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-02 02:35

I've seen some systems decide that the cutoff is 75; 75+ is 19xx and below is 20xx.

查看更多
地球回转人心会变
4楼-- · 2019-02-02 02:35

Why not have the original drop down on the page be a 2 digit value only? Credit cards only cover a small span when looking at the year especially if the CC vendor only takes in 2 digits already.

查看更多
相关推荐>>
5楼-- · 2019-02-02 02:35

Here is a link to a 4Guys article on how you can format Dates and Times using the ToString() method by passing in a custom format string.

http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=181

Just in case it goes away here is one of the examples.

'Create a var. named rightNow and set it to the current date/time
Dim rightNow as DateTime = DateTime.Now
Dim s as String 'create a string

s = rightNow.ToString("MMM dd, yyyy")

Since his link is broken here is a link to the DateTimeFormatInfo class that makes those formatting options possible.

http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx

It's probably a little more consistent to do something like that rather than use a substring, but who knows.

查看更多
Fickle 薄情
6楼-- · 2019-02-02 02:37
DateTime.Now.Year - (DateTime.Now.Year / 100 * 100)

Works for current year. Change DateTime.Now.Year to make it work also for another year.

查看更多
姐就是有狂的资本
7楼-- · 2019-02-02 02:38

This should work for you:

public int Get4LetterYear(int twoLetterYear)
{
    int firstTwoDigits =
        Convert.ToInt32(DateTime.Now.Year.ToString().Substring(2, 2));
    return Get4LetterYear(twoLetterYear, firstTwoDigits);
}

public int Get4LetterYear(int twoLetterYear, int firstTwoDigits)
{
    return Convert.ToInt32(firstTwoDigits.ToString() + twoLetterYear.ToString());
}

public int Get2LetterYear(int fourLetterYear)
{
    return Convert.ToInt32(fourLetterYear.ToString().Substring(2, 2));
}

I don't think there are any special built-in stuff in .NET.

Update: It's missing some validation that you maybe should do. Validate length of inputted variables, and so on.

查看更多
登录 后发表回答