Convert DateTime to MM/dd/yyyy in c#
c#, date, datetime
Solution
DateTime type have not any specific format you can directly save it to database. But if you want it as specific format string then you can do it by
//input date string as dd-MM-yyyy HH:mm:ss format
string date = "17-10-2016 20:00:00";
//dt will be DateTime type
DateTime dt = DateTime.ParseExact(date, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//s will be MM/dd/yyyy format string
string s = dt.ToString("MM/dd/yyyy");
and if you get input `date` as `DateTime` type then you can get formatted string directly
string s1 = date.ToString("MM/dd/yyyy");
Problem
I am calling the webservice which gives me the Datetime as "dd-MM-yyyy 00:00:00". Now i want to save it to the database. So in order to save the date, i have to convert the date format to MM/dd/yyyy. I have tried below code to convert the date time format, but nothing works for me ``` 1. DateTime.ParseExact(string, "MM/dd/yyyy", culture); 2. Convert.ToDateTime(string).ToString("MM/dd/yyyy",CultureInfo.InvariantCulture); ``` Can anyone help me on this?