Reputation: 71
I want to parse a date-time string into a DateTime
data type.
The format of the string is like 08/10/2013 09:49 PM
, and I want it to go to the form 2013-10-08 21:49:05.6500000
The following is my code but it's not working.
public static DateTime ConvertDateTime(String arg_dateTime)
{
try
{
return DateTime.ParseExact(arg_dateTime,
"dd/MM/yyyy H:m:s fff",
System.Globalization.CultureInfo.InvariantCulture);
}
catch(Exception exp)
{
return DateTime.Now;
}
}
Upvotes: 1
Views: 135
Reputation: 1503200
Your format string doesn't match your input data. Try a format string of "dd/MM/yyyy HH:mm:ss tt"
, and see the custom date and time format documentation for more information.
Note that rather than catching an exception if it fails, you should use DateTime.TryParseExact
and check the return value. Or if a failure here represents a big failure, just use ParseExact
and don't catch the exception. Do you really want to default to DateTime.Now
? It seems unlikely to me. You should strongly consider just letting the exception propagate up.
Also, your method doesn't return a particular format - it returns a DateTime
. That doesn't know anything about a format - if you want to convert the value to a specific format, you should do so specifically.
Upvotes: 2
Reputation: 73502
Is that you need to use ParseExact
only?
Why not Parse
?
string arg_dateTime = "2013-10-08 21:49:05.6500000";
var dt = DateTime.Parse(arg_dateTime, System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(dt);//this works
Here is the Demo
Upvotes: 0