System.DateTime在服务器中没有更新,但在本地工作正常

本文关键字:工作 更新 服务器 DateTime System | 更新日期: 2023-09-27 18:37:19

我编写了一些代码,根据基于位置的国家/地区下拉列表设置应用程序时间。它在本地工作正常,但部署后在服务器中不起作用,请帮助...

 Date Time AppTime = new DateTime();
  protected void Page_Load(object sender, EventArgs e)
  {  
   AppTime = new DateTime();
   //Time Zone Changes for other Countries            
   TimeZoneInfo tzi1 = TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time");
   DateTime IndTime = DateTime.Now;
   DateTime CurrentUTC = TimeZoneInfo.ConvertTimeToUtc(IndTime);
   DateTime OzzieTime = TimeZoneInfo.ConvertTimeFromUtc(CurrentUTC, tzi1);
  string SelectedCountry = ddlCountry.SelectedValue.ToString();
  string Australia = ConfigurationManager.AppSettings["AustraliaCountryID"];
  if (SelectedCountry == Australia)
  {       
    AppTime = OzzieTime;
  }
  else
  {       
    AppTime = IndTime;
  }
        TextBox1.Text = AppTime.ToString();
        TextBox2.Text = DateTime.UtcNow.ToString();
        TextBox3.Visible = OzzieTime.ToString();;

System.DateTime在服务器中没有更新,但在本地工作正常

您的代码需要做的就是:

string tzid = SelectedCountry == Australia
              ? "AUS Eastern Standard Time"
              : "India Standard Time";
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(tzid);
DateTime appTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz);

当然,你认为整个澳大利亚都在一个时区上,这是一个严重的错误。 有关详细信息,请参阅此维基百科文章。

当你将代码

发送到生产环境时,你的代码不起作用的原因可能是你依赖DateTime.Now是印度。 您的服务器很有可能位于另一个时区。 例如,最佳做法是将服务器置于 UTC 中。

此外,认为您的用户只会位于两个不同时区之一有点愚蠢。您可能应该通过 TimeZoneInfo.GetSystemTimeZones() 创建一个列表,使用每个项目的.Id.DisplayName

您可能还希望确保您的服务器具有最新的 Windows 更新,或者您已手动应用时区更新。

我遇到了同样的问题,我构建了这个方法:

    private static DateTime getTodayNow(string timeZoneId="")
    {
        DateTime retVal = DateTime.Now;

        DateTime.TryParse(DateTime.Now.ToString("s"), out retVal);
        if (!string.IsNullOrEmpty(timeZoneId))
        {
            try
            {
                DateTime now = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second).ToUniversalTime();
                TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);//"Russian Standard Time");
                retVal = TimeZoneInfo.ConvertTimeFromUtc(now, easternZone);
            }
            catch (TimeZoneNotFoundExceptio‌​n ex)
            {
              //write to log!!
            }
        }
        return retVal;
    }