Null Pointer
Null Pointer

Reputation: 9289

convert string to datetime in c#

I have a string strDate that contains selected date.

strDate holds value in the given format- month(3 letters) dd,yyyy

example 1: Feb 22, 2011

example 2: Jul 19, 2011

How can i convert this string value into datetime format of c#?

Upvotes: 0

Views: 1425

Answers (6)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174279

Have a look at DateTime.Parse. Try using:

DateTime.Parse(yourDateString, CultureInfo.GetCultureInfo("en-US"));

Upvotes: 4

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60684

Try this:

DateTime dt = DateTime.ParseExact(strDate, "MMM dd, yyyy", CultureInfo.InvariantCulture);

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

var str = "Jul 19, 2011";
DateTime date;
if (DateTime.TryParseExact(str, "MMM dd, yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
    // the parsing was successful
}

Upvotes: 1

Lloyd Powell
Lloyd Powell

Reputation: 18760

DateTime myDateTime;

if (DateTime.TryParse(myDateString, out myDateTime) == True)
{
  // successfully converted to date time
}

If you wrap it in a check of DateTime.TryParse then if there is a case where the string isn't of a correct DateTime format then an exception won't be thrown.

This way you can place an else statement of change to == False and respond to the failed parse. (instead of having to deal with en exception).

Upvotes: 1

Yoko Zunna
Yoko Zunna

Reputation: 1824

string myDateTimeString;

myDateTimeString = "19 Feb,2008";

DateTime dt;dt = Convert.ToDateTime(myDateTimeString);

Response.Write(dt.Day + "/" + dt.Month + "/" + dt.Year);

Upvotes: 0

Related Questions