[英]Changing System Date and Time Using DateTimePicker via C#?
I'm trying to change the time but when I try to change the time to 00:00 it becomes 08:00 instead? 我正在尝试更改时间,但是当我尝试将时间更改为00:00时,它将变为08:00? Is it considering my timezone which is UTC + 8?
是否考虑我的时区是UTC + 8?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace LibraryAdmin
{
public partial class Form41 : Form
{
public Form41()
{
InitializeComponent();
}
public struct SystemTime
{
public ushort Year;
public ushort Month;
public ushort DayOfWeek;
public ushort Day;
public ushort Hour;
public ushort Minute;
public ushort Second;
public ushort Millisecond;
};
[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
public extern static void Win32GetSystemTime(ref SystemTime sysTime);
[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
private void Form41_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SystemTime updatedTime = new SystemTime();
updatedTime.Year = (ushort)dateTimePicker1.Value.Year;
updatedTime.Month = (ushort)dateTimePicker1.Value.Month;
updatedTime.Day = (ushort)dateTimePicker1.Value.Day;
updatedTime.Hour = (ushort)((dateTimePicker2.Value.Hour)) ;
updatedTime.Minute = (ushort)dateTimePicker2.Value.Minute;
updatedTime.Second = (ushort)dateTimePicker2.Value.Second;
Win32SetSystemTime(ref updatedTime);
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
this.dateTimePicker2.Value.ToFileTimeUtc();
}
}
}
Yes, it's precisely because of the time zone issue. 是的,正是因为时区问题。 From the docs for
SetSystemTime
: 从
SetSystemTime
的文档中 :
Sets the current system time and date.
设置当前系统时间和日期。 The system time is expressed in Coordinated Universal Time (UTC).
系统时间以协调世界时(UTC)表示。
So if you're trying to change it to a particular local time, you should convert that to UTC first. 因此,如果您尝试将其更改为特定的本地时间,则应先将其转换为UTC。 For example:
例如:
private void button1_Click(object sender, EventArgs e)
{
var local = dateTimePicker1.Value;
var utc = local.ToUniversalTime();
SystemTime updatedTime = new SystemTime
{
Year = (ushort) utc.Year,
Month = (ushort) utc.Month,
Day = (ushort) utc.Day,
Hour = (ushort) utc.Hour,
Minute = (ushort) utc.Minute,
Second = (ushort) utc.Second,
};
Win32SetSystemTime(ref updatedTime);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.