Leopold Stotch
Leopold Stotch

Reputation: 1522

C# - Unable to set correct timezone

I am having an issue with an ASP.net website that is hosted on GoDaddy's shared hosting plan. The time seems to be different to GMT by 8 hours despite having the culture and UI culture set to the UK.

See this example:

Date.Now.ToString(New CultureInfo("en-GB")) & " - Culture: " + CultureInfo.CurrentCulture.Name + " - UI Culture: " + CultureInfo.CurrentUICulture.Name;

This outputs:

20/04/2015 10:16:17 - Culture: en-GB - UI Culture: en

The UK time when calling that statement was 18:16:17.

I've also tried with no culture:

  Date.Now.ToString("dd/MM/yyyy");

and with UtcNow instead:

Date.UtcNow.ToString(New CultureInfo("en-GB")) + " - Culture: " & CultureInfo.CurrentCulture.Name + " - UI Culture: " + CultureInfo.CurrentUICulture.Name;

But I still get the same incorrect time. Any help would be greatly appreciated.

Upvotes: 0

Views: 169

Answers (2)

LiamK
LiamK

Reputation: 815

As @artisdextrus says, the DateTime struct always always represents times in either the server local time or in UTC time. If you know the time zone of your end users, you can represent your end user local time with the DateTimeOffset class:

var myUsersTimeZone = "Central Standard Time";
var myServersTimeAsUtc = DateTime.UtcNow;
var myUsersTime = TimeZoneInfo.ConvertTimeFromUtc(
            myServersTimeAsUtc,
            TimeZoneInfo.FindSystemTimeZoneById(myUsersTimeZone));

Upvotes: 1

er_jack
er_jack

Reputation: 112

The timezone in ASP.net is the timezone of the nearest webserver you are using which could be in the next timezone. One way is to use JavaScript hour which gives the local time of the end user and subtract it from the UTC hour to get your local timezone.

<script type="text/javascript">
    window.onload = function () {
        var localTime = new Date();
        var hours = localTime.getHours();
        document.getElementById("<%=Hidden1.ClientID%>").value = hours;
    }
</script>

Default.aspx.cs

UTChour = DateTime.UtcNow.ToString("HH")
localHour = Hidden1.Value
timezone = UTChour - localHour

Upvotes: 1

Related Questions