DateTime奇怪的行为

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年有什么特别之处?

谢谢

瓦伦

最佳答案

您需要扩展您的解析格式字符串,以便您解析所有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());
 }

关于c# - C#DateTime奇怪的行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6837853/

10-11 22:37