Reputation: 1014
I have Window 7 installed in my computer. The problem is that the system date format is changed some time if computer is restarted. I need to make the date format fixed but don't know how. I have application built in mvc 3 and have code for string to datetime conversion. If system datetime format doesn't match with string it show error that
string is not in proper format
for converting into datetime which looks for system datetime. The exception is thrown in following code:
DateTime startDate = Convert.ToDateTime(start);
where,
string start = sundayOfLastWeek.ToString("MM/dd/yyyy HH:mm:ss");
Or, Is there any alternatives so that I can change in code that works all the time despite the system Date Time.
Upvotes: 0
Views: 2047
Reputation: 8686
As Habib already answered:
//Add any format you want or expect
string[] formats = { "MM/dd/yyyy HH:mm:ss", "dd.MM.yyyy HH:mm:ss" };
DateTime startDate = DateTime.ParseExact(start, formats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
It should help.
Upvotes: 0
Reputation: 223277
Use DateTime.ParseExact with the format "MM/dd/yyyy HH:mm:ss"
startDate = DateTime.ParseExact(start,
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
EDIT: based on comment from @John Woo
You can pass string array to DateTime.Parse like:
string[] dateFormats = new string[] { "MM/dd/yyyy HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "d/MM/yyyy" };
DateTime startDate = DateTime.ParseExact(start,
dateFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Upvotes: 4
Reputation: 2605
use .ToString(CultureInfo.InvariantCulture) and Parse(value, CultureInfo.InvariantCulture) for values persistance. Only omit CultureInfo if you render values for display purpose. For some specific data formats special formatting rules may exist - follow them.
to recover your data use ParseExact.
Upvotes: 1