C# DateTime strange behaviour
The output of the following piece of program is shown below:
for (int i = 0; i < 100; i++)
{
string year = i.ToString();
year = year.PadLeft(2, '0');
year = year + "0101";
DateTime pt = DateTime.ParseExact(year, "yyMMdd", null);
Console.WriteLine("{0}. {1}", i, pt.ToShortDateString());
}
Output:
0. 1/01/2000
1. 1/01/2001
2. 1/01/2002
3. 1/01/2003
4. 1/01/2004
5. 1/01/2005
6. 1/01/2006
7. 1/01/2007
8. 1/01/2008
9. 1/01/2009
10. 1/01/2010
11. 1/01/2011
12. 1/01/2012
13. 1/01/2013
14. 1/01/2014
15. 1/01/2015
16. 1/01/2016
17. 1/01/2017
18. 1/01/2018
19. 1/01/2019
20. 1/01/2020
2开发者_StackOverflow社区1. 1/01/2021
22. 1/01/2022
23. 1/01/2023
24. 1/01/2024
25. 1/01/2025
26. 1/01/2026
27. 1/01/2027
28. 1/01/2028
29. 1/01/2029
30. 1/01/1930 (Strange behavior starts from here)
31. 1/01/1931
32. 1/01/1932
33. 1/01/1933
34. 1/01/1934
35. 1/01/1935
36. 1/01/1936
37. 1/01/1937
38. 1/01/1938
39. 1/01/1939
40. 1/01/1940
41. 1/01/1941
42. 1/01/1942
43. 1/01/1943
44. 1/01/1944
45. 1/01/1945
46. 1/01/1946
47. 1/01/1947
48. 1/01/1948
49. 1/01/1949
50. 1/01/1950
51. 1/01/1951
52. 1/01/1952
53. 1/01/1953
54. 1/01/1954
55. 1/01/1955
56. 1/01/1956
57. 1/01/1957
58. 1/01/1958
59. 1/01/1959
60. 1/01/1960
61. 1/01/1961
62. 1/01/1962
63. 1/01/1963
64. 1/01/1964
65. 1/01/1965
66. 1/01/1966
67. 1/01/1967
68. 1/01/1968
69. 1/01/1969
70. 1/01/1970
71. 1/01/1971
72. 1/01/1972
73. 1/01/1973
74. 1/01/1974
75. 1/01/1975
76. 1/01/1976
77. 1/01/1977
78. 1/01/1978
79. 1/01/1979
80. 1/01/1980
81. 1/01/1981
82. 1/01/1982
83. 1/01/1983
84. 1/01/1984
85. 1/01/1985
86. 1/01/1986
87. 1/01/1987
88. 1/01/1988
89. 1/01/1989
90. 1/01/1990
91. 1/01/1991
92. 1/01/1992
93. 1/01/1993
94. 1/01/1994
95. 1/01/1995
96. 1/01/1996
97. 1/01/1997
98. 1/01/1998
99. 1/01/1999
Press any key to continue . . .
I am not sure as to what's special about 2029 or 2030 ?
Thanks
Varun
yyMMdd is a two digit year ie 01, 02 because it is two digits it needs to rollover at somepoint, and it rollback 100 years at 2030/1929. This what the millenium bug was, the solution is to have 4 digit years.
you are using 2-digit-year which is handled specially... see DateTime-type description for details http://msdn.microsoft.com/en-us/library/system.datetime.aspx / esp. http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/f9413b26-ce7b-43d8-aa15-85cf7b39b97e about 2-digit-years
Two digit date parsing is controlled by Calendar.TwoDigitYearMax. It's set by your locale, but basically it interprets any 2-digit year as being in the current century, say 1930-2029.
See Calendar.TwoDigitYearMax.
You need to expand your parsing format string, so you get all 4 digits parsed. And also, I dont see much sense in your code... try something like this:
for (int i = 2000; i < 2100; i++)
{
string year = i + "0101";
DateTime pt = DateTime.ParseExact(year, "yyyyMMdd", null);
Console.WriteLine("{0}. {1}", (i-1999), pt.ToShortDateString());
}
精彩评论