将一年从4位数转换为2位数再转换回C#

Mik*_*lls 54 c# datetime 2-digit-year

我的信用卡处理器要求我从信用卡到期日发送两位数的年份.以下是我目前的处理方式:

  1. DropDownList在页面上放了一个4位数的年份.
  2. 我在DateTime字段中验证到期日期,以确保传递给CC处理器的到期日期未过期.
  3. 我将两位数的年份发送到CC处理器(根据需要).我通过DDL年份的值的子字符串来完成此操作.

是否有方法将四位数年份转换为两位数年份.我没有在物体上看到任何东西DateTime.或者我应该像我一样继续处理它?

bro*_*lum 98

如果您使用到期日期(月/年)创建DateTime对象,则可以在DateTime变量上使用ToString(),如下所示:

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

编辑:如果在验证期间使用DateTime对象,请注意日期.如果有人选择05/2008作为他们卡的到期日期,它将在5月底到期,而不是在第一次到期.

  • 我用'%100`代表最后两位数,查看[this](http://stackoverflow.com/a/9803798/2218697) (5认同)
  • 是的,我检查大于或等于是否被视为有效。 (2认同)

Zbi*_*dro 32

第一个解决方案(最快):

yourDateTime.Year % 100
Run Code Online (Sandbox Code Playgroud)

第二种解决方案(在我看来更优雅):

yourDateTime.ToString("yy")
Run Code Online (Sandbox Code Playgroud)

  • 当您只有一个整数年而不是DateTime时,您的第一个解决方案很有用. (6认同)

Sad*_*han 9

答案已经给出.但在这里我想补充一些东西.有人告诉它没用.

可能是你正在使用

DateTime.Now.Year.ToString("yy");

这就是为什么它不起作用.我也犯了同样的错误.

将其更改为

DateTime.Now.ToString("yy");


Seb*_*son 5

这应该适合你:

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));
}
Run Code Online (Sandbox Code Playgroud)

我不认为.NET中有任何特殊的内置东西.

更新:它缺少您可能应该做的一些验证.验证输入变量的长度,等等.