Datetime.ParseExact Method


G

Guest

Hi.

I have a string: "11/24/2006 23:59" named StartDateTime

I need the string to be converted into a DateTime object in the following
format: 2006-11-24 11:59 PM

I tried the following: DateTime.ParseExact(StartDateTime,"yyyy-MM-dd HH:mm
tt*", System.Globalization.CultureInfo.CurrentCulture)

When StartDateTime = "11/24/2006 23:55" the date returned = 0000-00-00 00:00

When StartDateTime = "11/24/2006 3:00 AM", I get the following error:

System.FormatException: String was not recognized as a valid DateTime.


Any help any of you can offer would be greatly appreciated. Thanks!
 
Ad

Advertisements

R

Rad [Visual C# MVP]

Hey Erica,

The parameters passed to ParseExact are as follows:
1) The actual date, StartDateTime
2) The format the StartDateTime is CURRENTLY in,
3) The culture (or null)

So what you want to try is this:

//
// Get our date
//
string StartDateTime = "11/24/2006 23:59";
//
// Create a datetime object
//
DateTime myDate = DateTime.ParseExact(StartDateTime,"MM/dd/yyyy H:mm",
null);
//
// Capture our desired format in a string
//
string FormattedDate = myDate.ToString("yyyy-MM-dd HH:mm tt");
//
// Now we can use it as we please
//
Console.WriteLine(FormattedDate);

What you want to do is this:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top