c# - Parse datetime in multiple formats -


i have created api end-point. caller may call api post method passing relevant parameters. in parameters there 1 parameter of datetime format.

the problem when calling api caller may passes datetime in 3 different formats:

  1. long int - e.g. 1374755180
  2. us format - e.g. "7/25/2013 6:37:31 pm" (as string)
  3. timestamp format - e.g. "2013-07-25 14:26:00" (as string)

i have parse datetime value , convert datetime or string in timestamp format.

i have tried using datetime.tryparse(), datetime.parse(), convert.todatetime() , convert.todouble() none of them working in certainty me.

the required output has in en-gb format.

edit:

i had thought have if-else if-else block use tryparse 3 times 1 else string not parsed. best solution? or there solutions better this?

please help!

you should consider requiring timezone. 1 doesn't need it, #2 , #3 do.

public datetime parserequestdate() {     // https://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c      cultureinfo enus = new cultureinfo("en-us");      var dt = "1374755180";     //var dt = "7/25/2013 6:37:31 pm";     //var dt = "2013-07-25 14:26:00";      datetime datevalue;     long dtlong;      // scenario #1     if (long.tryparse(dt, out dtlong))         return dtlong.fromunixtime();      // scenario #2     if (datetime.tryparseexact(dt, "mm/dd/yyyy hh:mm:ss tt", enus, datetimestyles.none, out datevalue))         return datevalue;      // scenario #3     if (datetime.tryparseexact(dt, "yyyy-mm-dd hh:mm:ss", enus, datetimestyles.none, out datevalue))         return datevalue;      throw new someexception("don't know how parse..."); } 

edit matt johnson points out, datetime.tryparseexact accepts array of format strings. 2 & 3 condensed.

public datetime parserequestdate() {     // https://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c      cultureinfo enus = new cultureinfo("en-us");      var dt = "1374755180";     //var dt = "7/25/2013 6:37:31 pm";     //var dt = "2013-07-25 14:26:00";      datetime datevalue;     long dtlong;      // scenario #1     if (long.tryparse(dt, out dtlong))         return dtlong.fromunixtime();      // scenario #2 & #3     var formatstrings = new string[] { "mm/dd/yyyy hh:mm:ss tt", "yyyy-mm-dd hh:mm:ss" };     if (datetime.tryparseexact(dt, formatstrings, enus, datetimestyles.none, out datevalue))         return datevalue;      throw new someexception("don't know how parse..."); } 

the epoch conversion borrowed question. (an extension method)

public static class myextensions {     public static datetime fromunixtime(this long unixtime)     {         var epoch = new datetime(1970, 1, 1, 0, 0, 0, datetimekind.utc);         return epoch.addseconds(unixtime);     } } 

Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -