Mik*_*lls 54 c# datetime 2-digit-year
我的信用卡处理器要求我从信用卡到期日发送两位数的年份.以下是我目前的处理方式:
DropDownList在页面上放了一个4位数的年份.DateTime字段中验证到期日期,以确保传递给CC处理器的到期日期未过期.是否有方法将四位数年份转换为两位数年份.我没有在物体上看到任何东西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月底到期,而不是在第一次到期.
Zbi*_*dro 32
第一个解决方案(最快):
yourDateTime.Year % 100
Run Code Online (Sandbox Code Playgroud)
第二种解决方案(在我看来更优雅):
yourDateTime.ToString("yy")
Run Code Online (Sandbox Code Playgroud)
答案已经给出.但在这里我想补充一些东西.有人告诉它没用.
可能是你正在使用
DateTime.Now.Year.ToString("yy");
这就是为什么它不起作用.我也犯了同样的错误.
将其更改为
DateTime.Now.ToString("yy");
这应该适合你:
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中有任何特殊的内置东西.
更新:它缺少您可能应该做的一些验证.验证输入变量的长度,等等.
| 归档时间: |
|
| 查看次数: |
129608 次 |
| 最近记录: |