parsing - Parse very long date format to DateTime in C# -


how parse following string date datetime object in c#:

"thursday, 1st january 1970"

this coming xml feed , datetime.parse doesnt seem in en-gb locale. feed ever come british server i'm not worried globalization issues

my initial brute force approach to:

  • delete , including comma, , trailing space leave "1st january 1970"
  • then remove "st", "nd", "rd" or "th" appropriate leave "1 january 1970"
  • then convert month numeric equivalent leaving "1 1 1970"
  • then replace spaces "/" "1/1/1970"

im sure there must far more elegant way though? couldnt datetime.prse or datetime.parseexact work

just provide different take on this, , give idea of other options have; can specify format datetime.parse (or tryparse in example) account circumstances this, without trying 'pre format' string else string.replace calls , like;

public datetime parseordinaldatetime(string dt) {     string[] expectedformats =       datetime d;     if (datetime.tryparseexact(dt, "dddd, d\"st\" mmmm yyyy", null, datetimestyles.none, out d))         return d;     if (datetime.tryparseexact(dt, "dddd, d\"nd\" mmmm yyyy", null, datetimestyles.none, out d))         return d;     if (datetime.tryparseexact(dt, "dddd, d\"rd\" mmmm yyyy", null, datetimestyles.none, out d))         return d;     if (datetime.tryparseexact(dt, "dddd, d\"th\" mmmm yyyy", null, datetimestyles.none, out d))         return d;      throw new invalidoperationexception("not valid datetime string"); } 

the reason i'd propose approach sets out input expectations clearly, , contains behaviour single method. if format changes, can specify different format string in here , account new date time string structure.

or, slight variation on above, taking account below comments;

private static datetime parseordinaldatetime(string dt) {     string[] expectedformats = new[]     {         "dddd, d'st' mmmm yyyy",         "dddd, d'nd' mmmm yyyy",         "dddd, d'rd' mmmm yyyy",         "dddd, d'th' mmmm yyyy"     };      try     {         return datetime.parseexact(dt, expectedformats, null, datetimestyles.none);     }     catch (exception e)     {         throw new invalidoperationexception("not valid datetime string", e);     } } 

note: reason catch , throw invalidoperationexception above protect caller having catch exception handle whatever possible exceptions datetime.parseexact may throw. modify api.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -