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

六眼飞鱼酱① 提交于 2019-11-30 02:38:25

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.

1st solution (fastest) :

yourDateTime.Year % 100

2nd solution (more elegant in my opinion) :

yourDateTime.ToString("yy")

The answer is already given. But here I want to add something. Some person told that it did not work.

May be you are using

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

that is why it is not working. I also made the same the mistake.

Change it to

DateTime.Now.ToString("yy");

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.

At this point, the simplest way is to just truncate the last two digits of the year. For credit cards, having a date in the past is unnecessary so Y2K has no meaning. The same applies for if somehow your code is still running in 90+ years.

I'd go further and say that instead of using a drop down list, let the user type in the year themselves. This is a common way of doing it and most users can handle it.

Use the DateTime object ToString with a custom format string like myDate.ToString("MM/dd/yy") for example.

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

V.K.D Baghel
//using java script
var curDate = new Date();
var curYear = curDate.getFullYear();
curYear = curYear.toString().slice(2);
document.write(curYear)
//using java script
//using sqlserver
select Right(Year(getDate()),2)
//using sql server
//Using c#.net 
DateTime dt = DateTime.Now;
            string curYear = dt.Year.ToString().Substring(2,2).ToString()  ;
//using c#.net
Phiplex
DateTime.Now.Year - (DateTime.Now.Year / 100 * 100)

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

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.

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.

This is an old post, but I thought I'd give an example using an ExtensionMethod (since C# 3.0), since this will hide the implementation and allow for use everywhere in the project instead or recreating the code over and over or needing to be aware of some utility class.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

public static class DateTimeExtensions
    {
        public static int ToYearLastTwoDigit(this DateTime date)
        {
            var temp = date.ToString("yy");
            return int.Parse(temp);
        }
    }

You can then call this method anywhere you use a DateTime object, for example...

var dateTime = new DateTime(2015, 06, 19);
var year = cob.ToYearLastTwoDigit();

The answer is quite simple:

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

This seems to work okay for me. yourDateTime.ToString().Substring(2);

Even if a builtin way existed, it wouldn't validate it as greater than today and it would differ very little from a substring call. I wouldn't worry about it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!