Siva Siva - 2 months ago 6
C# Question

Retaining MM/DD/YYYY format in String

I need to write date in MM/DD/YYYY format. From a Date Picker Control. I try to assign it to a DateTime variable. Before Writing it to a file I assign it to a string. I see the value stored in String variable is in DD/MM/YYYY format.

Below is assignment statement

DateTime startTime, endTime;
string startTimeDate = "";
startTime = Convert.ToDateTime(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"));
endTime = Convert.ToDateTime(dpEndTime.Value.ToString("MM/dd/yyyy HH:mm"));
startTimeDate = startTime.ToString("MM/dd/yyyy HH:mm");
startTimeDate = startTimeDate.Replace('-', '/');


I observe startTimeDate is stored as DD/MM/YYYY only. startTime is storing as MM/DD/YYYY format only. Please let me know if there is any other approach to correctly assign / convert the date values.

Thanks in Advance

Answer

Edit:

You are losing the original date in your Convert.DateTime() conversion, you have to apply the format string here as well e.g. using DateTime.ParseExact :

startTime = DateTime.ParseExact(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"),
                                "MM/dd/yyyy HH:mm", 
                                CultureInfo.InvariantCulture);
Comments