Casting String to DateTime
I have a string in format
Jul 13 2011 1:07PM
I want to cast it as
dd/MM/yyyy HH:mm tt
e.g: 13/7/2011 11:49:00 AM //string=Jul 13 2011 1:07PM
I am using following code to cast it to date.
DateTime date = Convert.ToDateTime(Convert.ToDateTime(myDateString).ToString("dd/MM/yyyy HH:mm:ss"));
This works fine if my day in my string is less than 13
Jul 12 2011 1:07PM //this will cast to desire format fine!
Jul 13 2011 1:07PM //gives error String was not recognized as a valid DateTime.
I开发者_如何学C understand that it is taking day as month but I can not found a way to cast it to desire format.
See DateTime.ParseExact
:
DateTime date = DateTime.ParseExact(myDateString, "MMM dd YYYY H:mmtt", CultureInfo.InvariantCulture);
See also Time Format Strings
You should use DateTime.TryParse
DateTime dt ;
if (DateTime.TryParse("Jul 13 2011 1:07PM",out dt))
MessageBox.Show("Converted to Date object");
Post that you use the ToString()
method to get the desired output
dt.ToString("dd/MM/yyyy HH:mm")
First, convert the string Jul 13 2011 1:07PM
to a date:
var date = Convert.ToDateTime("Jul 13 2011 1:07PM");
Then, convert it to a string in the format you like:
var dateText = date.ToString("dd/MM/yyyy HH:mm:ss");
I believe you're searching for this:
Date.ParseExact("Jul 13 2011 1:07PM", "MMM d yyyy h:mmtt", Globalization.CultureInfo.InvariantCulture)
精彩评论