What will be timezone in central time zone machine, when a asp.net (aspx) page is called from eastern timezone server

huangapple go评论73阅读模式
英文:

What will be timezone in central time zone machine, when a asp.net (aspx) page is called from eastern timezone server

问题

GETDATE() 在用户从中部时区访问页面时会检索并显示中部时区的日期和时间,还是东部时区的日期和时间?

英文:

I have a SQL Server 2016 in Eastern timezone and there is a stored procedure and it has a call to GETDATE(). ASP.NET page calls this stored procedure; the ASP.NET app is deployed on a server also in Eastern timezone.

If the user accesses the page from Central time zone and will GETDATE() retrieve and show Central timezone date&time, or Eastern timezone date&time?

答案1

得分: 0

GETDATE() 在你的数据库服务器上执行,如果部署在东部时区,它始终会向世界上任何客户(Web)应用返回东部时间。

所以在处理多个时区时,我认为最好选择只在数据库中存储UTC/GMT日期/时间值,然后让客户端进行转换并显示其本地日期/时间。示例:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    SqlCommand cmd = new SqlCommand("SELECT GETUTCDATE() AS UTC", connection);
    using (SqlDataReader sqlDataReader = cmd.ExecuteReader())
    {
        while (sqlDataReader.Read())
        {
            DateTime utcFromDatabase = (DateTime)sqlDataReader["UTC"];
            DateTime mylocalTime = utcFromDatabase.ToLocalTime();
            myLabel.Text = string.Format("UTC:{0}, Local:{1}", utcFromDatabase, mylocalTime);
        }
    }
}

显然,你不应忘记让客户端提交他们的日期时间值为UTC(而不是本地时间)。但使用这种方法可以使你将数据库服务器迁移到完全不同的大陆而无需担心客户端日期时间格式问题。

英文:

GETDATE() is executed on your database server, which, if deployed in the Eastern timezone always returns the Eastern time to any client (web) application anywhere in the world.

So IMHO when dealing with multiple timezones it is better to choose to only store UTC/GMT date/time values in the database and have the clients convert that and display their local date/time. Example:

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand cmd = new SqlCommand("SELECT GETUTCDATE() AS UTC", connection);
        using (SqlDataReader sqlDataReader = cmd.ExecuteReader())
        {
            while (sqlDataReader.Read())
            {
                DateTime utcFromDatabase = (DateTime)sqlDataReader["UTC"];
                DateTime mylocalTime = utcFromDatabase.ToLocalTime();
                myLabel.Text = string.Format("UTC:{0}, Local:{1}", utcFromDatabase, mylocalTime);
            }
        }
    }

Obviously you should not forget to have the clients submit their datetime values as UTC (not local) as well. But using this approach enables you to move your database server to an entire different continent without client datetime formatting issues.

huangapple
  • 本文由 发表于 2020年1月3日 13:17:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/59573527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定