将 DateTimePicker 绑定到 UTC,但在本地时间显示和操作 [英] Bind DateTimePicker to UTC, but display and manipulate in local time
问题描述
我在 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?
推荐答案
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 handleFormat
event of the binding and convert the value to local time usingToLocalTime
method ofDateTime
- 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 fromDateTimePicker
back to universal time usingToUniversalTime
您可以在文档中了解有关这些事件的更多信息:
You can learn more about those events in docs:
示例
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屋!