I'm trying to change the time but when I try to change the time to 00:00 it becomes 08:00 instead? Is it considering my timezone which is 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
:
Sets the current system time and date. The system time is expressed in Coordinated Universal Time (UTC).
So if you're trying to change it to a particular local time, you should convert that to UTC first. 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);
}
See more on this question at Stackoverflow