I usually try to stick to this when dealing with DateTime
/string
transitions:
- When persisting dates in a text format, format it explicitly. Preferably to a standardized format (such as ISO 8601).
- When reading the date back, parse it to a
DateTime
object using the same, explicitly defined format.
This way your code will not fail when used in places where the date format differs from yours, or if the file is created on one locale, and then parsed in another.
private static string DateToString(DateTime input)
{
return input.ToString("yyyy-MM-dd");
}
private static DateTime StringToDate(string input)
{
return DateTime.ParseExact(input, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}