I’m trying to format a list of datetime. One date is in the format same as what i provided but the factors are not in place. That line of code is given below. Can someone tell me how to skip the error for the below line?
Convert.ToDateTime("22-01-2013 00:00:00").ToString("yyyy-MM-dd");
I would avoid using
Convert.ToDateTimeto start with. I would suggest usingDateTime.TryParseor (preferrably)DateTime.TryParseExact. Both of these will return a value indicating whether the conversion succeeded, so you don’t need to start catching exceptions in order to skip bad data. For example:If you have multiple possible formats, you should consider using the overload of
TryParseExactwhich allows you to specify multiple formats in a single call.As well as the format, you should consider the culture you want to use. In the above code (and your code) it will use the executing thread’s culture. Is that always what you want? The culture can affect all kinds of things – usually if you’re specifying a custom format, you want to use the invariant culture. Otherwise you could end up using a non-Gregorian calendar unexpectedly, for example…
EDIT: If your input is always in the format
dd-MM-yyyy, then you should probably use: