Question

How to populate C# DateTime object from this "03-06-2012 08:00 am" string.

I'm trying some code of follwoing type:

DateTime lectureTime  = DateTime.Parse("03-06-2012 08:00 am");

I am using jQuery based this http://trentrichardson.com/examples/timepicker/ plugin to generate date time.

Update --

So many answers below and lot of stuff to clear basics for this small issue From the below snapshot u can see what I tried and what i received during debugging in visual studio enter image description here

Was it helpful?

Solution

You need to use DateTime.ParseExact. Something like

DateTime lectureTime  = DateTime.ParseExact("03-06-2012 08:00 am", "dd-MM-yyyy hh:mm tt", CultureInfo.InvariantCulture);

OTHER TIPS

string lectureTime = "03-06-2012 08:00 am";
DateTime time = DateTime.ParseExact(lectureTime , "dd-MM-yyyy hh:mm tt", CultureInfo.InvariantCulture);
  • dd: days [00-31]
  • MM: months [00-12]
  • yyyy: years [0000-9999]
  • '-': these are separated with a dash
  • hh: hours [00-12]
  • mm: minutes[00-60]
  • tt: time [am, pm] (case insensitive)

If you have the correct culture, your code works without modification. But you may be using a different date formatting from the program that generated the string.

I'd recommend always specifying a CultureInfo when:

  • Parsing a DateTime generated by another system.
  • Outputting a DateTime that will be parsed by another system (not just shown to your user).

Try this:

CultureInfo cultureInfo = new CultureInfo("en-GB"); // Or something else?
DateTime lectureTime  = DateTime.Parse("03-06-2012 08:00 am", cultureInfo);

See it working online: ideone

Difference between DateTime.Parse and DateTime.ParseExact

If you want .NET to make its best effort at parsing the string then use DateTime.Parse. It can handle a wide variety of common formats.

If you know in advance exactly how the dates should be formatted, and you want to reject anything that differs from this format (even if it could be parsed correctly and without ambiguity) then use DateTime.ParseExact.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top