Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to parse date string of format like 2013-09-17T05:15:27.947

I am trying to parse date of format:

2013-09-17T05:15:27.947

This is my code

String MessageRecieptDate = messageReceiptDate.Replace("T", " ").Remove(messageReceiptDate.Length-4);
DateTime dt = new DateTime();
IFormatProvider culture = new CultureInfo("en-US");
dt = DateTime.ParseExact(MessageRecieptDate, "dd MMM", culture);

But its giving some format exception every time. Seems I am missing something basic.

like image 453
Ankit Avatar asked Sep 09 '13 12:09

Ankit


2 Answers

I have no idea why you're using "dd MMM" as format string, when your date is "2014-02-03T19:00:00". There two formats have nothing in common.

Proper format string for your input is "yyyy-MM-ddTHH:mm:ss":

string value = "2014-02-03T19:00:00";
DateTime dateValue = DateTime.ParseExact(value, "yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
like image 153
MarcinJuraszek Avatar answered Sep 30 '22 12:09

MarcinJuraszek


What should work :

//without ParseExact
var t1= DateTime.Parse(dt);

//you don't know how many milliseconds will be in your string, 
//and want absolutely use ParseExact anyway
var t2= DateTime.ParseExact(dt.PadRight(27, '0'), "o", culture);

//you know you'll always have 3 chars for milliseconds.
var t3= DateTime.ParseExact(dt, "yyyy-MM-ddTHH:mm:ss.fff", culture);
like image 26
Raphaël Althaus Avatar answered Sep 30 '22 12:09

Raphaël Althaus