views:

33

answers:

2

Hey everyone,

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.

+1  A: 

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 http://stackoverflow.com/questions/3873281/how-to-convert-string-to-local-date-time/3873325#3873325

Brad
@Brad: Time zones are *also* simple if you only care about an instant in time, which it sounds like is the case here (representing when a task started or finished) - just represent everything as UTC.
Jon Skeet
Absolutely, Jon. Utc is the way to go. My point is to cause the user to consider time zones as being more of a problem that format. There's plenty built into .NET to consume/output different formats, but if you don't store time zone data (or store dates as UTC) then you aren't going to be able to be accurate.
Brad
+7  A: 

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 (i.e. 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.

Jon Skeet