We all think that the output string will follows the pattern which we asign to the parameter in ToString method. However, sometime you will get a strange result. You may consider the code and result below:
DateTime.Now.ToString("yyyyMMdd"); -> 20070607
DateTime.Now.ToString("yyyy-MM-dd"); -> 2007-06-07
DateTime.Now.ToString("yyyy/MM/dd"); -> 2007-06-07
DateTime.Now.ToString("yyyy年MM月dd日"); -> 2007年06月07日
DateTime.Now.ToString("yyyy~MM~dd"); -> 2007~06~07
DateTime.Now.ToString("yyyy-MM-dd"); -> 2007-06-07
DateTime.Now.ToString("yyyy/MM/dd"); -> 2007-06-07
DateTime.Now.ToString("yyyy年MM月dd日"); -> 2007年06月07日
DateTime.Now.ToString("yyyy~MM~dd"); -> 2007~06~07
watch out the third line and you may think that should not be happened. But I really met this kind of problem in Windows Server 2000 today.
Why it happened? Because it is caused by the setting of short time format in your OS. In Windows Server 2000, You could go to the "regional options" in control pannel then switch to "Date" tab. In the dialog window, there is a "Date separator" option. You need to modify it from any other to "/". (Check the image below.)

If you want to make sure that your program will get the right string format in any setting condition to any windows computer, then The only way is using an overwrite versoin of DateTime.ToString method and pass the "System.Globalization.DateTimeFormatInfo.InvariantInfo" as second parameter. So the ultimate solution which don't need to configure your OS setting to the third line above is:
DateTime.NowToString( "yyyy/M/d", System.Globalization.DateTimeFormatInfo.InvariantInfo );
then the result will be exactly 2007/06/07.
Very funny, right? Hope Microsoft will fix this problem in the future.
[re-post this article due to database crash.]
沒有留言:
張貼留言