简体   繁体   中英

C# parse regional date time strings

I am trying to make a small application for a project in which clients from across the world can use. The problem I am having is that the back-end is setup using XML files that gets generated and uploaded to a shared network and in these XML files I store a date time variable that says when a particular task started and finished. The program crashes at certain load intervals with a format exception and after some research I found out that I need to setup a regional date time parser.

The question that I have is how can I convert the time in the XML file, whether it's using US, AU, or UK regional settings, and have it use the client's local settings. This is being done using VS C# 2005 and the .NET 3.5 framework.

Thanks in advance for your help.

The backends should be writing in a standard format. The XML shouldn't just use the local date format - that way madness lies. The main point of XML is to be an interchange format for computers , not for humans . Unless you're formatting something for human consumption, you shouldn't be using local variation.

So either use a specific format everywhere, specifying CultureInfo.InvariantCulture when formatting, or use dt.ToString("o") or another of the culture-invariant format strings.

If you're just talking about a point in time (ie the local time doesn't matter, just the global instant) you should also make sure you use a consistent time zone, where UTC is the obvious choice. For example, use DateTime.UtcNow instead of DateTime.Now .

Once you've got the generation code doing sensible things, consuming it should be very straightforward.

If, however, you don't have the luxury of changing the generation code, you may have to resort to passing the right CultureInfo into DateTime.TryParseExact . However, this means that you'll need to know the culture used to create the file. If the files are being generated in a culture-sensitive way and you don't know which culture they're using, you're basically stuffed. For example, 03/05/2010 could mean March 5th 2010 or May 3rd 2010. Without any more information, you have no way of deciding which to use.

Regional settings implies format. This is not your main concern. Format is simple (use a DateTime.Parse or .ParseExact . Time zones should be your primary concern .

Please refer to How to convert string to local Date Time?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM