开发者

DateTime - How can i account for different delimiter characters

My application is taking the time now, formatting it into a string, and parsing it back to a valid DateTime value using ParseExact. See below for more details:

DateTime dt = DateTime.Now;
            DateTime timeNow = DateTime.Now;

            string timeStamp = dt.ToString("MM/dd/yyyy HH:mm:ss");


开发者_C百科            // To match different countries
            if (timeStamp.IndexOf("/") > -1)
            {
                timeNow = DateTime.ParseExact(timeStamp, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
            }
            else if (timeStamp.IndexOf(".") > -1)
            {
                timeNow = DateTime.ParseExact(timeStamp, "MM.dd.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
        }

Different countries use different date formats. Is there a way to make my application automatically take into account the different formats, rather than having to make a condition for each one that appears?

Thanks for any help,

Evan


If your application is using a string representation for dates internally, I would suggest using the Sortable format specifier when outputting it. That way, you always know that you can read it back using ParseExact and the "s" format specifier.

The only time you should output dates in any other format is when you need to display them for the user, or when some other program requires them in a particular format.

As @Mike Christensen pointed out in his comment, different locales will interpret dates differently. The default output for many European countries is DD/MM/YYYY, whereas in the U.S. it's usually MM/DD/YYYY. If you take the different locales into account, then there will be ambiguity.


You can pass an array of format specifiers with as many formats as you want to support.

string[] formats = new [] { "MM/dd/yyyy HH:mm:ss", "MM.dd.yyyy HH:mm:ss" };     
DateTime d = DateTime.ParseExact
                        (
                         timestamp, formats, 
                         CultureInfo.InvariantCulture,                        
                         DateTimeStyles.None);

However, since you say you are generating the strings yourself, why don't you just make sure you always format them using the InvariantCulture:

string timestamp = dt.ToString("MM/dd/yyyy HH:mm:ss", 
                               CultureInfo.InvariantCulture);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜