C#DateTime奇怪的行为

时间:2011-07-26 23:32:30

标签: c# datetime

以下程序的输出如下所示:

 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
21. 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 . . .

我不确定2029年或2030年有什么特别之处?

由于

Varun的

4 个答案:

答案 0 :(得分:4)

yyMMdd是一个两位数的年份,即01,02,因为它需要在某个点翻转两位数,并且它在2030/1929年回滚100年。这就是千禧虫,解决方案是有4位数的年份。

答案 1 :(得分:3)

您正在使用专门处理的2位数年份...有关详细信息,请参阅日期时间类型说明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约2位数年

答案 2 :(得分:3)

两位数日期解析由Calendar.TwoDigitYearMax控制。它由您的语言环境设置,但基本上它将任何2位数年份解释为当前世纪,例如1930-2029。

请参阅Calendar.TwoDigitYearMax

答案 3 :(得分:2)

您需要扩展解析格式字符串,以便解析所有4位数字。而且,我在你的代码中看不到多少意义......尝试这样的事情:

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());
 }