C# 将两位数的年份转换为四位数的年份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2024273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a two digit year to a four digit year
提问by Scott Chamberlain
This is a question of best practices. I have a utility that takes in a two digit year as a string and I need to convert it to a four digit year as a string. right now I do
这是一个最佳实践的问题。我有一个实用程序,它接受一个两位数的年份作为一个字符串,我需要将它转换为一个四位数的年份作为一个字符串。现在我做
//DOB's format is "MMM (D)D YY" that first digit of the day is not there for numbers 1-9
string tmpYear = rowIn.DOB.Substring(rowIn.DOB.Length - 3, 2); //-3 because it is 0 indexed
if (Convert.ToInt16(tmpYear) > 50)
tmpYear = String.Format("19{0}", tmpYear);
else
tmpYear = String.Format("20{0}", tmpYear);
I am sure I am doing it horribly wrong, any pointers?
我确定我做错了,有什么指示吗?
采纳答案by Vedran
The .NET framework has a method that does exactly what you want:
.NET 框架有一种方法可以满足您的需求:
int fourDigitYear = CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(twoDigitYear)
That way you will correctly adhere to current regional settings as defined in Control Panel (or group policy):
这样,您将正确遵守控制面板(或组策略)中定义的当前区域设置:
回答by martin clayton
Given that there are people alive now born before 1950, but none born after 2010, your use of 50 as the flipping point seems broken.
鉴于现在有人在 1950 年之前出生,但没有人在 2010 年之后出生,因此您将 50 用作转折点似乎已被打破。
For date of birth, can you not set the flip point to the 'year of now' (i.e. 10) in your app? Even then you'll have problems with those born before 1911...
对于出生日期,您不能在您的应用程序中将翻转点设置为“现在的年份”(即 10)吗?即便如此,1911 年之前出生的人也会遇到问题......
There's no perfect way to do this - you're creating information out of thin air.
没有完美的方法可以做到这一点——你是凭空创造信息。
I've assumed DOB = date-of-birth. For other data (say, maturity of a financial instrument) the choice might be different, but just as imperfect.
我假设 DOB = 出生日期。对于其他数据(例如,金融工具的成熟度),选择可能不同,但同样不完美。
回答by Ponkadoodle
It might be smarter to check tmpYear > currentYear%100. If it is, then it's 19XX, otherwise 20XX.
检查 tmpYear > currentYear%100 可能更聪明。如果是,则为 19XX,否则为 20XX。
回答by jdmichal
I think Java has a good implementation of this:
我认为 Java 有一个很好的实现:
http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#year
http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#year
People rarely specify years far into the future using a two-digit code. The Java implementation handles this by assuming a range of 80 years behind and 20 years ahead of the current year. So right now, 30 would be 2030, while 31 would be 1931. Additionally, this implementation is flexible, modifying its ranges as time goes on, so that you don't have to change the code every decade or so.
人们很少使用两位数的代码来指定未来几年。Java 实现通过假设当前年份落后 80 年和提前 20 年的范围来处理此问题。所以现在,30 是 2030,而 31 是 1931。此外,这个实现是灵活的,随着时间的推移修改它的范围,这样你就不必每十年左右更改一次代码。
I just tested, and Excel also uses these same rules for 2-digit year conversion. 1/1/29 turns into 1/1/2029. 1/1/30 turns into 1/1/1930.
我刚刚测试过,Excel 也使用这些相同的规则进行 2 位数年份转换。1/1/29 变成 1/1/2029。1/1/30 变成 1/1/1930。
回答by Leif
Out of curiosity, from where do you get this data? From a form? In that case; I would simply ask the user to fill in (or somehow select) the year with four digits or get the users age and month/day of birth, and use that data to figure out what year they were born. That way, you wouldn't have to worry about this problem at all :)
出于好奇,您从哪里获得这些数据?从形式?在这种情况下; 我会简单地要求用户用四位数字填写(或以某种方式选择)年份,或者获取用户的年龄和出生月份/日期,然后使用该数据来确定他们的出生年份。这样,您根本不必担心这个问题:)
Edit:Use DateTimefor working with this kind of data.
编辑:使用DateTime处理此类数据。
回答by FrenchData
You can also use the DateTime.TryParse method to convert your date. It uses the current culture settings to define the pivot year (in my case it is 2029)
您还可以使用 DateTime.TryParse 方法来转换您的日期。它使用当前的文化设置来定义枢轴年(在我的例子中是 2029)
DateTime resultDate;
Console.WriteLine("CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax : {0}", System.Globalization.CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax);
DateTime.TryParse("01/01/28", out resultDate);
Console.WriteLine("Generated date with year=28 - {0}",resultDate);
DateTime.TryParse("01/02/29",out resultDate);
Console.WriteLine("Generated date with year=29 - {0}", resultDate);
DateTime.TryParse("01/03/30", out resultDate);
Console.WriteLine("Generated date with year=30 - {0}", resultDate);
The output is:
输出是:
CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax : 2029
CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax:2029
Generated date with year=28 - 01/01/2028 00:00:00
生成日期为 year=28 - 01/01/2028 00:00:00
Generated date with year=29 - 01/02/2029 00:00:00
生成日期为 year=29 - 01/02/2029 00:00:00
Generated date with year=30 - 01/03/1930 00:00:00
生成日期为 year=30 - 01/03/1930 00:00:00
If you want to change the behavior you can create a culture with the year you want to use as pivot. This thread shows an example
如果你想改变行为,你可以用你想使用的年份作为支点来创建一种文化。这个线程显示了一个例子
DateTime.TryParse century control C#
But as martin stated, if you want to manage a time period that spans more than 100 year, there is no way to do it with only 2 digits.
但正如马丁所说,如果你想管理一个跨越 100 年以上的时间段,只有 2 位数字是没有办法做到的。
回答by Jags
Try this simple code
试试这个简单的代码
//Invoke TextBoxDateFormat method with date as parameter.
//以日期为参数调用TextBoxDateFormat方法。
Method
方法
public void TextBoxDateFormat(string str1)
{
// Takes the current date format if MM/DD/YY or MM/DD/YYYY
DateTime dt = Convert.ToDateTime(str1);
//Converts the requested date into MM/DD/YYYY and assign it to textbox field
TextBox = String.Format("{0:MM/dd/yyyy}", dt.ToShortDateString());
//include your validation code if required
}
回答by bizah
Had a similar issue, and came up with this... HTH!
有一个类似的问题,并想出了这个...... HTH!
value = this.GetDate()
if (value.Length >= 6)//ensure that the date is mmddyy
{
int year = 0;
if (int.TryParse(value.Substring(4, 2), out year))
{
int pastMillenium = int.Parse(DateTime.Now.ToString("yyyy").Substring(0, 2)) - 1;
if (year > int.Parse(DateTime.Now.ToString("yy")))//if its a future year it's most likely 19XX
{
value = string.Format("{0}{1}{2}", value.Substring(0, 4), pastMillenium, year.ToString().PadLeft(2, '0'));
}
else
{
value = string.Format("{0}{1}{2}", value.Substring(0, 4), pastMillenium + 1, year.ToString().PadLeft(2, '0'));
}
}
else
{
value = string.Empty;
}
}
else
{
value = string.Empty;
}
回答by Pawel Cioch
My answer will not match your question but for credit cards I just add 2 digits of current year
我的答案与您的问题不符,但对于信用卡,我只添加当前年份的 2 位数字
private int UpconvertTwoDigitYearToFour(int yearTwoOrFour)
{
try
{
if (yearTwoOrFour.ToString().Length <= 2)
{
DateTime yearOnly = DateTime.ParseExact(yearTwoOrFour.ToString("D2"), "yy", null);
return yearOnly.Year;
}
}
catch
{
}
return yearTwoOrFour;
}
回答by RealWillyWoka
The implementation of
实施
System.Globalization.CultureInfo.CurrentCulture.Calendar.ToFourDigitYear
is
是
public virtual int ToFourDigitYear(int year)
{
if (year < 0)
throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (year < 100)
return (this.TwoDigitYearMax / 100 - (year > this.TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year;
else
return year;
}
Hope this helps!
希望这可以帮助!