Thursday, April 28, 2011

"DateTime.Now" - why does it return GMT?

I am running on a Win2003 server, TimeZone set to (GMT -06:00) Central Time. I am programming with VS.NET 2005, f/x 2.x. When I execute the following code I do not get the expected results - but only when it is on the PROD server. Any other machine appears to work correctly.

_response.Timestamp = DateTime.Now;

Is there a setting hidden somewhere that can do this to .NET web apps? I looked through all the configs I could find but did not see anything right off.


NOTE: This is happening on all of our servers...


NOTE: I tried using a date passed in to my page:

[parameter 3] (Date): Thu Nov 05 22:23:16 MST 2009  // Web client time
LastPlayed (Date): Fri Nov 06 05:23:16 MST 2009  // Simple boxing of value

public class FlashObject
{
    #region Declarations
    public DateTime LastPlayed;
    public List<PlayList> Characters;
    public List<PlayList> Variations;
    #endregion
}

The above object is simply hydrated like this:

internal static void GetPlayer(FlashObject flashObject, DateTime clientPlayTime)

Notice they are both in MST (Mountain Standard Time)!! :(

From stackoverflow
  • what is _request?

    Internally, on the HttpContext object, reflector shows this code:

    public DateTime get_Timestamp() { return this._utcTimestamp.ToLocalTime(); }

    Keith Barrows : _request is an object I defined in my app. It is mainly a struct type object with further struct type objects and collections inside. THere are no methods and it is intended just to carry well formed data around the app.
  • After a lot of research I have changed my DateTime variables into DateTimeOffset variables. I also changed the Flash/Flex code to pass in a TZ Name and Offset. With this information I can track client times accurately.

    private void SetUserInfo(DateTimeOffset ClientTime, int Offset)
    {
        if (Offset != 0 && ClientTime.DateTime == ClientTime.UtcDateTime)
        {
            ClientTime = ClientTime.AddHours(Offset);
            _actionDateTime = new DateTimeOffset(ClientTime.DateTime, new TimeSpan(Offset, 0, 0));
        }
        else
            _actionDateTime = ClientTime;
    
        _actionUtcDateTime = new DateTimeOffset(_actionDateTime.DateTime.ToUniversalTime(), new TimeSpan(0, 0, 0));
    }
    

    With the above bit of code I can now save client time as well as UTC time.

    Chris Charabaruk : As anyone who deals with time in .NET applications should, so long as they're using .NET 3.5 or newer. Unfortunately, those still targeting older versions of the CLR are buggered.

0 comments:

Post a Comment