Thursday, March 26, 2009

Specify a Date Format on The Fly

I write DICOM migration software in C#, and was recently faced with the task of setting a date format on the fly so that I could convert any date to DICOM format.

After much Googling, I found that DateTime has a TryParseExact() method that will allow you to specify the source string date format and put the successfully parsed date into a previously defined DateTime object. Once it was here, it was easy to use ToString() to format it DICOM-style.


CultureInfo enUS = new CultureInfo("en-US");
DateTime dt;
if (DateTime.TryParseExact(txtDateToConvert.Text, txtDateFormat.Text.Trim(), enUS, DateTimeStyles.None, out dt))
{
if (null != dt)
txtDICOMdate.Text = dt.ToString("yyyyMMdd");
}