【问题标题】:Using the specific timezone instead of the server timezone使用特定时区而不是服务器时区
【发布时间】:2020-11-12 16:37:25
【问题描述】:

GridView

  DateTimeOffset serverTime = DateTimeOffset.Now;
         
            DateTimeOffset localTime = TimeZoneInfo.ConvertTime(serverTime, TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time"));


     if (localTime.Date >= eddate.Date && localTime.Date <= stdate.Date)
            {
                if (localTime >= sttime && localTime <= edtime)
                {

                    MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
                    MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
                    MySqlDataReader MyReader2;
                    MyConn2.Open();
                    MyReader2 = MyCommand2.ExecuteReader();
                    Label2.Text = "Thank you for You Vote";
                    //  System.Diagnostics.Debug.WriteLine();

                }
                else
                {
                    Label2.Text = "Please check the eletion time!";
                    Label2.ForeColor = System.Drawing.Color.Yellow;
                }
            }
            else
            {
                Label2.Text = "Please check the eletion date !";
                Label2.ForeColor = System.Drawing.Color.Purple;
            }

我正在尝试获取我指定的时区(新加坡标准时间)中的日期,并将其与我在 gridview 中显示的日期进行比较。我可以在验证时间时使用新加坡标准时间。但是,对于日期,它仍然无法获得新加坡标准时间的日期。

【问题讨论】:

  • DateTime 对时区一无所知。它只是一个没有偏移的日期+时间值。如果您关心时区,请使用DateTimeOffsetDateTime 可以是UTCLocalUnknown,任何来自外部系统(如数据库)的值都被视为Unknown
  • 我可以使用'DateTimeOffset'来获取我指定的时区(中国标准时间)的日期吗?因为我的本地时间与中国标准时间相同,所以我想使用中国标准时间而不是托管服务器时间
  • 嗨,我现在正在使用 DateTimeOffSet。我仍然无法在特定时区获得正确的日期
  • 没有理由为 Date 和 DateTime 设置单独的变量。您可以从 DateTime 获取日期
  • 再次显示代码,使用DateTimeOffsetonly。不要在任何地方使用DateTime

标签: c# asp.net datetime


【解决方案1】:

此代码将服务器时间转换为新加坡时间。

DateTimeOffset serverTime = DateTimeOffset.Now;
DateTimeOffset singaporeTime = TimeZoneInfo.ConvertTime(serverTime,
  TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time"));

不要在代码中使用DateTime任何地方,只使用DateTimeOffset

此外,没有理由为日期和时间设置单独的变量。 DateTimeOffset 就是您所需要的。 (使用.Date 属性从DateTimeOffset 获取日期)

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 2014-08-05
    • 2012-11-08
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多