DateTime.Parse changes format

I'll try to illustrate an example:

var dateNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");

produces: 10/01/2014 21:50:34

var dateNowParse = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));

produces: 10/01/2014 9:50:34 PM

QUESTION:

How to parse the date, and keep formatting like: dd/MM/yyyy HH:mm:ss, with an 24 hour format, without any PM

Thank you!

Update 1

Sorry maybe my question wasn't so clear, i'll try to explain the real situation below.

Please do not focus on real meaning of DateTime.Now, suppose we have a string variable in the format of 10/01/2014 21:50:34, and then I try to parse it, and store the result in another variable. What I am willing to achieve is to keep the result in a DateTime variable which has the exact formatting 10/01/2014 21:50:34.

Now here is a snippet:

var stringDate = "10/01/2014 22:50:30";
DateTime parsedDate = DateTime.Parse(stringDate, CultureInfo.InvariantCulture);
//parsedDate result is: 10/01/2014 10:50:30 PM

What is frustrating me is:

  1. In the stringDate the 22:50 hour says that the string is formatted to the 24 hour clock. (the 12 clock format uses hours counter up to 12)

  2. If I used 22:50, Isn't logically that the output should'nt use any AM PM and 12 hour format?

Jon Skeet
people
quotationmark

How to parse the date, and keep formatting

You need to keep the format alongside the DateTime if you want to. A DateTime does not have any concept of being in a particular format. The value of the DateTime returned by Parse isn't "10/01/2014 9:50:34 PM" - it's that particular date and time, but not a string representation.

You could have a type which maintains the two together - or if you always want to format in the same way, just specify that format explicitly when you format, without keeping it as data with the DateTime value.

Personally I would try to stick to DateTime.ParseExact where feasible, as I find it easier to predict what it will do - but it does depend on your input. If it's input with a particular format that you're expecting, ParseExact really is the way forward, potentially with the invariant culture to avoid any cultural differences.

people

See more on this question at Stackoverflow