将 DateTimePicker 绑定到 UTC,但在本地时间显示和操作 [英] Bind DateTimePicker to UTC, but display and manipulate in local time

查看:28
本文介绍了将 DateTimePicker 绑定到 UTC,但在本地时间显示和操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Windows 窗体中有一个 DateTimePicker,我希望将它绑定到一个 UTC DateTime 值.但即使我使用 DateTime.SpecifyKind() 来确保将 Kind 值设置为 UTC,DateTimePicker 控件也不会以本地时间显示该值.有没有办法向用户显示当地时间并允许他们在本地时间操作该值,而绑定的值仍为 UTC?

I have a DateTimePicker in Windows Forms that I wish to bind to a UTC DateTime value. But even though I use DateTime.SpecifyKind() to make sure the value Kind is set to UTC, the DateTimePicker control does not display the value in Local time. Is there a way to present the local time to the user and allow them to manipulate the value in their local time, while the binded value remains in UTC?

推荐答案

您可以依赖 Format解析 事件 绑定 对象.

You can rely on Format and Parse event of the Binding object.

因此,假设您在数据源中有世界时:

So, assuming you have universal time in data source:

  • 要在 DateTimePicker 中显示本地时间,您应该处理绑定的 Format 事件并使用 ToLocalTime DateTime
  • 的方法
  • 要将世界时间放回数据源,您应该处理绑定的Parse 事件并将来自DateTimePicker 的本地时间转换回世界时间使用 ToUniversalTime
  • To show the local time in DateTimePicker, you should handle Format event of the binding and convert the value to local time using ToLocalTime method of DateTime
  • To put the universal time back to the data source, you should handle Parse event of the binding and convert the local time which is coming from DateTimePicker back to universal time using ToUniversalTime

您可以在文档中了解有关这些事件的更多信息:

You can learn more about those events in docs:

  • Format:当控件的属性绑定到数据值时发生.
  • Parse:当数据绑定控件的值改变时发生.

示例

DataTable dt = new DataTable();
private void Form4_Load(object sender, EventArgs e)
{
    dt.Columns.Add("Column1", typeof(DateTime));

    dateTimePicker1.DataBindings.Add("Value", dt, "Column1");
    dateTimePicker1.DataBindings["Value"].Format += 
        (s, a) => a.Value = ((DateTime)a.Value).ToLocalTime();
    dateTimePicker1.DataBindings["Value"].Parse += 
        (s, a) => a.Value = ((DateTime)a.Value).ToUniversalTime();

    dt.Rows.Add(new DateTime(2000, 1, 1, 13, 0, 0));
}
private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(dt.Rows[0]["Column1"].ToString());
}

这篇关于将 DateTimePicker 绑定到 UTC,但在本地时间显示和操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆