簡體   English   中英

C#DateTime奇怪的行為

[英]C# DateTime strange behaviour

下面的程序片段的輸出如下所示:

 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年有什么特別之處?

謝謝

瓦倫

yyMMdd是兩位數的年份,即01、02,因為它是兩位數,需要在某個時間點進行展期,並在2030/1929年回溯100年。 這就是千年蟲,解決的辦法是有4位數字的年。

您使用的是特殊處理的兩位數年份...有關詳細信息,請參見DateTime類型說明http://msdn.microsoft.com/zh-cn/library/system.datetime.aspx / esp。 http://social.msdn.microsoft.com/Forums/zh-CN/netfxbcl/thread/f9413b26-ce7b-43d8-aa15-85cf7b39b97e大約2位數年

兩位數的日期解析由Calendar.TwoDigitYearMax控制。 它是由您的語言環境設置的,但是基本上它會將19世紀至2029年這樣的兩位數字年份解釋為當前世紀。

請參閱Calendar.TwoDigitYearMax

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM