1

I want to convert a String to Datetime. I'm getting an error This is not a valid datetime.

The string I want to convert and code are as follows.

string date1 = "9/13/2012 5:26:06 PM"; TimePart = DateTime.ParseExact(date1, "M/d/yyyy HH:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture); 
2

5 Answers 5

6

I think it should be M/dd/yyyy h:mm:ss tt in your format parameter.

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

6 Comments

No. Even that is not working. Error is String was not recognized as a valid DateTime.
@ShamiC i just updated the answer, since you have added tt, it is not in 24-hr format anymore. so change HH into hh
@JohnWoo - And since hh expects a leading 0 for a single digit hour, you need to remove the extra h.
This is inaccurate without @Oded's correction. Why is it getting so many upvotes? (I downvoted)
@TimS. you're right. I updated it after Oded's correction. Am I not allow to update the answer? If I have the ability to change the upvotes of my answer. I will give it all to you. :)
|
3

It looks like your format is really M/d/yyyy h:mm:ss tt. The difference is h (12-hour, with only as many digits as needed) instead of HH (24-hour, with leading 0 to pad to 2 digits).

If the input format can vary at all, you should use DateTime.Parse instead so that you don't have to tell it the exact format. ParseExact is faster, and requires that it matches the specified format, which may be preferable in your cast.

Comments

2

You need to use the lowercase h:

DateTime TimePart = DateTime.ParseExact( date1, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); Console.WriteLine(TimePart); // 09/13/2012 17:26:06 

Uppercase "H" is 24-hour time, lowercase "h" is 12-hour time with AM/PM.

Comments

2

You should be using a lower case h for a 12 hour clock (since you have an AM/PM designator).

Additionally, you should only use one h, as you don't have a leading 0 to the hours, and hh expects it.

A format string that works:

"M/d/yyyy h:mm:ss tt" 

Comments

1

It looks like the HH isn't matching the "5". Try h.

1 Comment

This really should be a comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.