通过C#使用DateTimePicker更改系统日期和时间?

时间:2017-08-05 13:17:32

标签: c#

我试图改变时间但是当我尝试将时间改为00:00时,它变成了08:00而不是?是考虑我的时区是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();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

是的,正是因为时区问题。来自docs for SetSystemTime

  

设置当前系统时间和日期。系统时间以协调世界时(UTC)表示。

因此,如果您尝试将其更改为特定的本地时间,则应首先将其转换为UTC。例如:

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);
}