1

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;
    }
}
2
  • delete the ':s' from the parsing template Commented Oct 8, 2013 at 16:36
  • Do you believe that "08/10/2013 09:49 PM" matches the format "dd/MM/yyyy H:m:s fff"? Look at it carefully. Commented Oct 8, 2013 at 16:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

The input string is 08/10/2013 09:49 PM, but it should still work.
What I meant was that you are using the output format as the input for your example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.