Reputation: 63
Can someone please explain why the following code outputs "4/14/2013 8:00:00 PM"?
var dt = "2013-04-15+00:00";
var result = DateTime.Parse(dt);
Upvotes: 3
Views: 964
Reputation: 518
The MSDN documentation describes this in depth.
http://msdn.microsoft.com/en-us/library/1k1skd40(v=vs.90).aspx
It is reading in the string in UTC because of the +00:00. It is printing out in localtime.
Upvotes: 0
Reputation: 61912
The "+00:00"
part of your string is interpreted as the time zone. That is a "geographical" zone of 0 hours and 0 minutes to the east of Greenwich.
If you intended the "+00:00"
part to be the time of day instead, use a format string, like so:
var dt = "2013-04-15+00:00";
var result = DateTime.ParseExact(dt, "yyyy-MM-dd+HH:mm", CultureInfo.InvariantCulture);
The "HH"
and "mm"
means hours and minutes of the (local) time of day. In the opposite direction, with "yyyy-MM-ddzzz"
, the "+00:00"
part will mean time zone.
Upvotes: 0
Reputation: 7356
At a guess, I think Anthony Pergram's comment is right. Most likely it is interpreting the string as a date, "2013-04-15", a timezone of "+00:00" which is GMT, and no time-of-day. The default time-of-day is midnight, so the resulting date is equal to "2013-04-15 at midnight GMT". That is then converted to your local timezone, which is four hours behind GMT, and output as you see.
If you can, you should use a more precise date/time format such as ISO 8601, which would look like "2013-04-15T00:00:00Z", or "2013-04-15T00:00:00-04:00"
Upvotes: 1
Reputation: 3573
That is because it is taking your system timezone into account. It then adjust the specified time appropriately
Upvotes: 0
Reputation: 203802
There are many ways of formatting dates/times in different regions, cultures, contexts, etc. When using DateTime.Parse
it will do its best to guess what to do, but it will often be unsuccessful in cases where there are ambiguities in determining which datetime format is appropriate.
You can use DateTime.ParseExact
in order to specify the exact formatting that the string is using to format the date.
Upvotes: 1