Date and Time Separator Is the Same Thing

by Warlock on Oct.14, 2008, under Uncategorized

I’ve been sitting on this one for a while, but a little quirk in the implementation of DateTime.Parse method is that the date separator and time separator cannot be the same thing. It’s documented at this MSDN article:
http://msdn2.microsoft.com/en-us/library/1k1skd40.aspx

Despite the fact that it’s a “feature” it can be a gotcha if you ever run into it.

using System;
using System.Text;
using System.Globalization;

namespace DateTimeSeparatorSameThingDemo
{
	class Program
	{
		static void Main(string[] args)
		{
			DateTimeFormatInfo invariantDTFI = CultureInfo.InvariantCulture.DateTimeFormat;
			DateTimeFormatInfo localizedDTFI = CultureInfo.CurrentUICulture.DateTimeFormat;

			Console.WriteLine("Invariant Date Separator: " + invariantDTFI.DateSeparator);
			Console.WriteLine("Invariant Time Separator: " + invariantDTFI.TimeSeparator);

			Console.WriteLine();

			Console.WriteLine("Localized Date Separator: " + localizedDTFI.DateSeparator);
			Console.WriteLine("Localized Time Separator: " + localizedDTFI.TimeSeparator);

			Console.WriteLine();

			Console.WriteLine("Using Default Culture Settings To Localized: ");
			Console.WriteLine(DateTime.Now.ToString());
			Console.WriteLine();

			// Uncomment the following line to throw exception when DateSeparator is the
			// same as the time separator, as configured in the windows regional settings
			//Console.WriteLine(DateTime.Parse(DateTime.Now.ToString()).ToString());

			Console.WriteLine();

			// This is the correct way to send a date/time to a string and re-parse it.
			string tmpDateTime = DateTime.Now.ToString(invariantDTFI);
			DateTime parsedDateTime = DateTime.Parse(tmpDateTime, invariantDTFI);

			// Using ToString without a DateTimeFormatInfo will display the date time
			// in the localized format, but it's better to be explicit
			Console.WriteLine("Displaying the parsed DateTime as expected by the user:");
			Console.WriteLine(parsedDateTime.ToString(localizedDTFI));

			// Wait for user to view the results
			Console.ReadLine();
		}
	}
}

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...