如何在c#中获取当前用户时区 [英] How to get current user timezone in c#

查看:164
本文介绍了如何在c#中获取当前用户时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 MVC3 中构建一个应用程序,当用户进入我的网站时,我想知道该用户的时区.我想知道如何在 c# 中而不是在 javaScript 中执行此操作?

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?

推荐答案

如前所述,您需要您的客户端告诉您的 ASP.Net 服务器有关它们所在时区的详细信息.

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

这是一个例子.

我有一个 Angular 控制器,它从我的 SQL Server 数据库以 JSON 格式加载记录列表.问题是,这些记录中的 DateTime 值位于 UTC 时区,我想向用户显示其本地时区的日期/时间.

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.

我使用 JavaScriptgetTimezoneOffset()" 函数确定用户的时区(以分钟为单位),然后将此值附加到我尝试调用的 JSON 服务的 URL:

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;
    });
}

在我的 ASP.Net 代码中,我提取了 timezoneOffset 参数...

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.

有点乱,因为我想在数据库中的每条记录上调用我的 C# FromUTCData 函数,但是 LINQ to SQL 不能将原始 SQL 与 C# 函数结合起来.

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.

解决方案是先读入记录,然后遍历它们,将时区偏移量应用到每条记录中的 DateTime 字段.

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;
}

虽然它运行良好,但在编写 Web 服务以向世界不同地区的用户显示日期/时间时,此代码非常有用.

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.

现在,我在苏黎世时间上午 11 点写这篇文章,但如果你在洛杉矶阅读它,你会发现我在凌晨 2 点(你的当地时间)编辑了它.使用这样的代码,您可以让您的网页显示对您网站的国际用户有意义的日期时间.

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.

呸.

希望这会有所帮助.

这篇关于如何在c#中获取当前用户时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆