convert string to datetime format and date only in c#
c#, datetime
Solution
You need to parse the string first - you have missed out the AM/PM designator. Take a look at Custom Date and Time Format Strings on MSDN:
DateTime firstdate = DateTime.ParseExact(startdatestring,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
Then you can format to a string:
var firstDateString = firstdate.ToString("MM-dd-yyyy");
Which you may also want to do with `InvariantCulture`:
var firstDateString = firstdate.ToString("MM-dd-yyyy",
CultureInfo.InvariantCulture);
Problem
How can I convert the string to datetime. I have following string: ``` 08/19/2012 04:33:37 PM ``` I want to convert above string to following format date: ``` MM-dd-yyyy ``` and ``` dd/MM/yyyy HH:mm:ss ``` I have been trying to convert using different technique and using following: ``` DateTime firstdate = DateTime.Parse(startdatestring); ``` It shows following error String was not recognized as a valid DateTime. I have search for it and couldn't get exact solution and also try using different format for datetime. Please how can I convert above string to above date format