Developer
Developer

Reputation: 3057

Convert strings to specified date formats

I am unable to convert strings to date with throwing exceptions of not proper format:

here are the patterens:

    DD-MM-YYYY
    MM-DD-YYYY
    YYYY-DD-MM
    YYYY-MM-DD
    YYYYDDMM
    YYYYMMDD

formats are coming from dropdown list and here is what I tried different method but still its throwing exceptions:

 strCurrentFormat = rcboDateFormat.SelectedValue.ToString();

                 DateTime db = DateTime.ParseExact(strOldDate, "DD-MM-YYYY", CultureInfo.InvariantCulture);

                 //DateTime loadedDate = DateTime.ParseExact(strOldDate, strCurrentFormat, null);

I have solved this problem before by taking string, split them and move the year and month and day around to proper format but that would take long time, if anyone knows an easier way it would be a tremendous help.

Upvotes: 1

Views: 1403

Answers (3)

Oded
Oded

Reputation: 499002

Two things:

First - use the correct format strings. D and Y are not known format specifiers. d and y are.

Second - you can put your formats into a string array and use the ParseExact overload that takes that list of formats.

string[] formats = new string[] 
   {"dd-MM-yyyy",
    "MM-dd-yyyy",
    "yyyy-dd-MM",
    "yyyy-MM-dd",
    "yyyyddMM",
    "yyyyMMdd"};

DateTime db = DateTime.ParseExact(strOldDate, 
                                  formats, 
                                  CultureInfo.InvariantCulture,
                                  DateTimeStyles.None);

The formats will be attempted in order.

Upvotes: 5

John Koerner
John Koerner

Reputation: 38077

Your format string is wrong.

You need lowercase for "d" and "y", so

dd-MM-yyyy

Read all about the format string on MSDN.

Upvotes: 1

user222427
user222427

Reputation:

Taken from http://www.codeproject.com/Articles/14743/Easy-String-to-DateTime-DateTime-to-String-and-For

d - Numeric day of the month without a leading zero. dd - Numeric day of the month with a leading zero. ddd - Abbreviated name of the day of the week. dddd - Full name of the day of the week.

f,ff,fff,ffff,fffff,ffffff,fffffff - Fraction of a second. The more Fs the higher the precision.

h - 12 Hour clock, no leading zero. hh - 12 Hour clock with leading zero. H - 24 Hour clock, no leading zero. HH - 24 Hour clock with leading zero.

m - Minutes with no leading zero. mm - Minutes with leading zero.

M - Numeric month with no leading zero. MM - Numeric month with a leading zero. MMM - Abbreviated name of month. MMMM - Full month name.

s - Seconds with no leading zero. ss - Seconds with leading zero.

t - AM/PM but only the first letter. tt - AM/PM ( a.m. / p.m.)

y - Year with out century and leading zero. yy - Year with out century, with leading zero. yyyy - Year with century.

zz - Time zone off set with +/-.

Upvotes: 1

Related Questions