C# 计算时差的时间和日期

C# Work out time and date with timezone difference

我 运行 遇到了一个小问题,我正在连接到 Pokerstars.com 数据源以获取有关预定扑克锦标赛信息的更新 (https://www.pokerstars.com/datafeed/tournaments/all.xml)

然后我解析信息并将其存储在我的 Winforms 应用程序的 listView 中,但是我需要计算出正确的时间,包括本地时区差异。我知道 Pokerstars 服务器在 -05:00 运行,但我的问题是将它转换为我应用程序的特定用户的正确时间。

有人可以编写代码将其转换为该用户的本地时间,以便显示正确的开始时间。这是我用来读取 XML 文件的代码:

    private void LoadAllTournaments()
    {
        DataSet ds = new DataSet();
        ds.ReadXml("http://46.101.5.145/Feeds/all.xml");

        ListViewItem item;

        foreach (DataRow dr in ds.Tables["tournament"].Rows)
        {

            StartDate = dr["start_date"].ToString();

            if (dr["play_money"].ToString() != "true")
            {

                FPPFee = Convert.ToInt32(dr["fpp_fee"]);

                if (FPPFee == 0)
                {

                    if (dr["buy_in_fee"].ToString() != "[=10=] + [=10=]")
                    {

                        item = new ListViewItem(new string[] { dr["name"].ToString(), StartDate.Substring(0, 10), StartDate.Substring(12, 7), dr["buy_in_fee"].ToString(), dr["prize"].ToString(), dr["players"].ToString(), dr["status"].ToString(), dr["id"].ToString()});
                        listView1.Items.Add(item);

                    }

                }

            }

        }

    }

作为记录,我连接到我自己的服务器来读取文件,因为 Pokerstars 只允许来自英国的人查看 XML 文件,所以他们每 10 次下载到我的英国 VPS分钟。

首先,您必须将 StartDate 解析为日期时间。我不知道字符串是什么,你可能需要更精确地解析它,但一般来说:

DateTime origDate = DateTime.Parse(StartDate);

然后只需从中添加或减去小时数即可获得所需的时区。例如:

DateTime newDate =   origDate.AddHours(-1);

减去一小时。

在xml中,提供的值如:

<start_date>2015-11-02T12:50:00-05:00</start_date>

因此,您不需要预知服务器的时区,因为偏移量已编码在数据中。只需将字符串解析为 DateTimeOffset, then use TimeZoneInfo 即可转换为用户的时区。

DateTimeOffset startDate = DateTimeOffset.ParseExact(
    (string) dr["start_date"],
    "yyyy-MM-dd'T'HH:mm:sszzz",
    CultureInfo.InvariantCulture);

TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTimeOffset converted = TimeZoneInfo.ConvertTime(startDate, tz);

在上面的例子中 "GMT Standard Time" 是伦敦的 Windows 时区标识符,冬天使用 GMT (UTC+00:00),BST (UTC+01:00)在夏天。当然,您需要知道哪个时区实际适用于您的用户。

稍后在您的代码中您使用 Substring 提取部分日期 - 您不应该这样做,而应该使用格式化字符串。例如,converted.ToString("d") 表示日期,converted.ToString("t") 表示时间。请参阅 MSDN 中的 standard and custom 格式化字符串。