【问题标题】:Convert date to utc using the timezone passed from client(javascript)使用从客户端传递的时区将日期转换为 UTC(javascript)
【发布时间】:2018-11-03 14:01:38
【问题描述】:

我有一个逻辑可以在管理员提到的特定时间段内在用户屏幕上显示一条消息。

var time = DateTime.SpecifyKind(System.DateTime.Now, DateTimeKind.Unspecified);
var date= TimeZoneInfo.ConvertTimeToUtc(time, TimeZoneInfo.FindSystemTimeZoneById(System.TimeZoneInfo.Local.Id));
StringBuilder dispalyMessage = new StringBuilder("<marquee scrolldelay='90' behavior='scroll' scrollamount='1' direction='left'><b><ul>");
var bannerMessageIds = new HashSet<int>(db.CompanyBanners.Where(c => c.CompanyId == PortalUser.Current.CurrentCompanyId).Select(x => x.BannerMessageId));
List<BannerMessage> bannerMessages = db.BannerMessages.Where(p => bannerMessageIds.Contains(p.Id)  && (p.StartDate < date && p.EndDate > date) ).ToList();

这里的问题是我正在转换时间以使用服务器时区进行检查。

有没有办法将客户端时区从 javascript 传递到 c# 并根据该时区转换日期。

我的意思是这样的

var date= TimeZoneInfo.ConvertTimeToUtc(time, TimeZoneInfo.FindSystemTimeZoneById("time zone id passed from client javascript"));

【问题讨论】:

  • 您的数据库应该以 UTC 格式存储时间,因此您应该与 DateTime.UtcNow 进行比较,而不需要任何时区转换。

标签: c# asp.net datetime utc


【解决方案1】:

我认为没有。但是您可以像下面这样在 JavaScript 中获取时区偏移量。

function myFunction() {
var d = new Date();
var n = d.getTimezoneOffset();
document.getElementById("demo").innerHTML = n;
}

这应该符合您的目的。

【讨论】:

  • 是的。我知道。但是有没有办法在服务器端获取客户端时区?我知道这不是一个直接的问题。
【解决方案2】:

客户端

  Create a script that will be executed at every time the page loads.
    In the script check if the cookie that stores timezone offset exists.
    If the cookie not exists check whether the browser supports cookie.
    If the browser supports cookie create a new one and store the timezone offset.
    Reload the page if the cookie is created for the first time or expired.
    If the timezone cookie already exists check if the current timezone and the one stored in cookie are same. 
If they are different then overwrite with new timezone and reload the page.

服务器端

    Read the cookie value on every request and store it in session.
    Create a utility method that converts the passed datetime in UTC to the client timezone by adjusting it with the offset read from session.
  If there is no value in session possibly the browser doesn’t supports cookie then convert the date-time to server timezone.

Look here for complete implantation and more hints

【讨论】:

    【解决方案3】:

    如果您将日期时间以 UTC 格式存储在数据库中,则不必在意。所以除非我错过了什么(总是可能的:)),你能不能只查询 DateTime.UtcNow 的值,而不是在这部分进行任何时区转换?

    例如 用户的时区,现在是 13:00。
    服务器的时区,现在是 10:00。
    UTC 时间是 09:00。

    当您将时间存储在数据库中时,您将输入的日期/时间从用户的时区转换为 UTC(在 javascript 或服务器端),因此用户输入的 13:00 时间以 UTC 形式存储为09:00。

    当用户随后点击该页面时,您希望找到所有应该“现在”显示的消息。对用户来说“现在”是 13:00,但在 UTC 中是 09:00。因此,应该只需要根据该 UTC 时间进行搜索。

    【讨论】:

      猜你喜欢
      • 2016-06-17
      • 1970-01-01
      • 2017-11-02
      • 2021-03-12
      • 2016-02-17
      • 2021-01-04
      • 2014-06-13
      • 2021-04-29
      • 2017-11-07
      相关资源
      最近更新 更多