I have a string that has a date stored in it.
String date = \"03-05-2013 00:00:00\";
I parsed it to Datetime as follows:
Da
You need to pass the format in the ToString()
call.
Start.ToString("dd-MM-yyy HH:mm:ss");
The format you parse with does not dictate how the DateTime
is formatted when you convert the date back to a string. When you call ToString
on a date it pulls the format from the current culture of the thread your code is executing on (which defaults to the culture of the machine your on).
You can override this by passing the format into ToString()
i.e.
Start.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
See Custom Date and Time Formats.
I need to keep the original formatting.
Then you need to apply the same pattern again when you call ToString
:
string formatted = Start.ToString("dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(Note that you should specify the same culture when formatting as you did when parsing, to avoid things like the time separator from changing.)
Note that for some formats this still might not give the exact original representation - if you're using a format which includes the text for a month, for example, that would match case-insensitively, so input including "MARCH" would be reformatted as "March".
A DateTime
value is just a date and time (and a "kind", but that's another story) - it doesn't maintain a textual representation any more than an integer does. It's important to differentiate between the inherent data in a value and a textual representation of that data. Most types which have multiple possible textual representations have no notion of keeping "the original representation" alongside the data.