Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current user timezone in c#

I am building an application in MVC3 and when a user comes into my site I want to know that user's timezone. I want to know how to do this in c# not in javaScript?

like image 520
Ahsan Attari Avatar asked Nov 19 '11 12:11

Ahsan Attari


People also ask

How do I find the timezone of a user?

getTimezoneOffset()/60; The method getTimezoneOffset() will subtract your time from GMT and return the number of minutes. So if you live in GMT-8, it will return 480. To put this into hours, divide by 60.

How do I find my local time zone?

To get the current browser's time zone, you can use the getTimezoneOffset() method from the JavaScript Date object. The getTimezoneOffset() returns the time difference, in minutes, between UTC time and local time.

How do I get the timezone from DateTime?

DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means. DateTimeOffset is somewhat better - that's basically a UTC time and an offset.

How do I get local timezone offset?

The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.


1 Answers

As has been mentioned, you need your client to tell your ASP.Net server details about which timezone they're in.

Here's an example.

I have an Angular controller, which loads a list of records from my SQL Server database in JSON format. The problem is, the DateTime values in these records are in the UTC timezone, and I want to show the user the date/times in their local timezone.

I determine the user's timezone (in minutes) using the JavaScript "getTimezoneOffset()" function, then append this value to the URL of the JSON service I'm trying to call:

$scope.loadSomeDatabaseRecords = function () {      var d = new Date()     var timezoneOffset = d.getTimezoneOffset();      return $http({         url: '/JSON/LoadSomeJSONRecords.aspx?timezoneOffset=' + timezoneOffset,         method: 'GET',         async: true,         cache: false,         headers: { 'Accept': 'application/json', 'Pragma': 'no-cache' }     }).success(function (data) {         $scope.listScheduleLog = data.Results;     }); } 

In my ASP.Net code, I extract the timezoneOffset parameter...

int timezoneOffset = 0;  string timezoneStr = Request["timezoneOffset"]; if (!string.IsNullOrEmpty(timezoneStr))     int.TryParse(timezoneStr, out timezoneOffset);  LoadDatabaseRecords(timezoneOffset); 

... and pass it to my function which loads the records from the database.

It's a bit messy as I want to call my C# FromUTCData function on each record from the database, but LINQ to SQL can't combine raw SQL with C# functions.

The solution is to read in the records first, then iterate through them, applying the timezone offset to the DateTime fields in each record.

public var LoadDatabaseRecords(int timezoneOffset) {     MyDatabaseDataContext dc = new MyDatabaseDataContext();      List<MyDatabaseRecords> ListOfRecords = dc.MyDatabaseRecords.ToList();      var results = (from OneRecord in ListOfRecords            select new            {                ID = OneRecord.Log_ID,                Message = OneRecord.Log_Message,                StartTime =  FromUTCData(OneRecord.Log_Start_Time, timezoneOffset),                EndTime = FromUTCData(OneRecord.Log_End_Time, timezoneOffset)            }).ToList();      return results; }  public static DateTime? FromUTCData(DateTime? dt, int timezoneOffset) {     //  Convert a DateTime (which might be null) from UTC timezone     //  into the user's timezone.      if (dt == null)         return null;      DateTime newDate = dt.Value - new TimeSpan(timezoneOffset / 60, timezoneOffset % 60, 0);     return newDate; } 

It works nicely though, and this code is really useful when writing a web service to display date/times to users in different parts of the world.

Right now, I'm writing this article at 11am Zurich time, but if you were reading it in Los Angeles, you'd see that I edited it at 2am (your local time). Using code like this, you can get your webpages to show date times that make sense to international users of your website.

Phew.

Hope this helps.

like image 61
Mike Gledhill Avatar answered Oct 03 '22 07:10

Mike Gledhill