DateTime parsing C# -


i cant parse date, whats wrong?

 "jul 15 2015 16: +0"  

+0 utc added time, want time full in seconds.

utc

console.writeline("date: {0}",      datetime.parseexact("jul 15 2015 16: +0",      "mmm dd yyyy hh", cultureinfo.invariantculture).tostring("mmm dd, yyyy")); 

error:

string not recognized valid datetime

full code:

using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using newtonsoft.json; using newtonsoft.json.linq; using system.globalization;  namespace consoleapplication3 {     class program     {         static void main(string[] args)         {             string json = "{\"success\":true,\"price_prefix\":\"\",\"price_suffix\":\" pСѓР±.\",\"prices\":[[\"jul 15 2015 16: +0\",1.745,\"6\"],[\"jul 15 2015 17: +0\",1.78,\"5\"],[\"jul 15 2015 18: +0\",1.65,\"7\"]]}";             var prices = jobject.parse(json)["prices"].children()                             .select(j => new priceitem                             {                                 date = (string)j[0],                                 price = (float)j[1],                                 count = (int)j[2]                             });             foreach (priceitem priceitem in prices)             {                 console.writeline("date: {0}", datetime.parseexact(priceitem.date, "mmm dd yyyy hh", cultureinfo.invariantculture).tostring("mmm dd, yyyy"));                 console.writeline("price: {0}", priceitem.price);                 console.writeline("count: {0}", priceitem.count);                 console.writeline(new string('-', 10));             }                console.readkey(true);         }     }      class priceitem     {         public string date { get; set; }         public float price { get; set; }         public int count { get; set; }     } } 

datetime.parseexact that, exactly parses input data. if input data doesn't match, throw exception (although there similar function called datetime.tryparseexact won't throw).

your input data jul 15 2015 16: +0 includes time zone , separator character. want create format string matches it, need use mmm dd yyyy hh':' z. colon inside ' marks because interpreted time separator character parser, need tell formatter "copy literal" input string.

your code becomes:

console.writeline("date: {0}",      datetime.parseexact("jul 15 2015 16: +0",      "mmm dd yyyy hh':' z", cultureinfo.invariantculture).tostring("mmm dd, yyyy")); 

and should work.

see custom datetime format strings (msdn) more information.


Comments