Date and Time Separator Is the Same Thing

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 Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>