Reputation: 15973
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 understand that it is taking day as month but I can not found a way to cast it to desire format.
Upvotes: 2
Views: 2059
Reputation: 17058
See DateTime.ParseExact
:
DateTime date = DateTime.ParseExact(myDateString, "MMM dd YYYY H:mmtt", CultureInfo.InvariantCulture);
See also Time Format Strings
Upvotes: 4
Reputation: 2790
I believe you're searching for this:
Date.ParseExact("Jul 13 2011 1:07PM", "MMM d yyyy h:mmtt", Globalization.CultureInfo.InvariantCulture)
Upvotes: 1
Reputation: 75609
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");
Upvotes: 1
Reputation: 38210
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")
Upvotes: 1