Reputation: 306
I have an ASP.Net form with a date/time control on it. If the form is posted back due to validation errors, the date/time is converted to the servers timezone and set as the value in the date/time control - causing the original timezone information to be lost.
I am using DateTime.TryParse
which parses the date into the server time and seems to be losing the original timezone. I want to check if the page is a PostBack and skip the server timezone conversion if at all possible - so I keep the original value.
I tried using TryParseExact
which has the timezone information however I couldn't work out what format I should be sending in.
string hiddenDateTime = "2019-09-01T18:28:00.000+0800";
DateTime dateValue;
DateTime.TryParse(hiddenDateTime, CultureInfo.CurrentCulture,
DateTimeStyles.None, out dateValue);
Is there a way to stop this conversion to local from happening and keeping the original timezone?
Upvotes: 6
Views: 2860
Reputation: 98810
First of all, this is how DateTime.TryParse method works;
If s contains no time zone information, result contains a DateTime value whose Kind property is DateTimeKind.Unspecified when the method returns. If the string to be parsed contains time zone information, result contains a DateTime value whose Kind property is DateTimeKind.Local when the method returns.
DateTime
object itself neither keep timezone information nor keep UTC Offset value. When you use some parsing operations on a string, it is usually normal to lost these values.
It is not clear what value you try to get exactly but I suggest a few things to get;
DateTimeStyles.AdjustToUniversal
instead of DateTimeStyles.None
, you will get a DateTime as 9/1/2019 10:28:00 AM
which has Utc
as a Kind
property since this enum value is exactly what this for.DateTimeOffset
instead of DateTime
. With parsing to DateTimeOffset
, you can keep both of them on it's Offset
and DateTime
properties.Upvotes: 10