开发者

Trying to set PC clock programmatically just before Daylight Saving Time ends

To reproduce :

1) Add Microsoft.VisualBasic assembly to your project reference

2) Change PC timezone to : (GMT+10:00) Canberra, Melbourne, Sydney . Ensure PC is set to automatically adjust clock for daylight savings time. (For this timezone, daylight savings time ends at 3am on 4 Apr 2010.)

3) add following code :

    public void SetNewDateTime(DateTime dt)
    {
        Microsoft.VisualBasic.DateAndTime.Today = dt; // ignores time component
        Microsoft.VisualBasic.DateAndTime.TimeOfDay = dt;  // ignores date component
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DateTime dt = new DateTime(2010, 4, 5, 5, 0, 0);  // XX
        SetNewDateTime(dt);  // XX

        System.Threading.Thread.Sleep(500);

        DateTime dt2 = new DateTime(2010, 4, 4, 1, 0, 0);
        SetNewDateTime(dt2);
    }

4) When button 1 is clicked, the PC clock eventually shows 2am, whereas 1 am was expected. (If code marked at "XX" is removed, the clock sometimes shows the correct time of 1 am).

Any idea what is happening ? (Or is there a more reliable way of setting the PC clock from C# code ?)

TIA.

EDIT :

In response to David M, I tried some modified code :

    private void button1_Click(object sender, EventArgs e)
    {
        DateTime dt = new DateTime(2010, 4, 5, 5,0,0, DateTimeKind.Unspecified);
        SetNewDateTime(dt);

        System.Threading.Thread.Sleep(500);

        // type : 2010-04-04T01:00:00 into textBox1

        DateTime dt2 = System.Xml.XmlConvert.ToDateTime(textBox1.Text, System.Xml.XmlDateTimeSerializationMode.Unspecified);

        SetNewDateTime(dt2);
    }

This get开发者_JS百科s the DateTime input from a textBox. The result was the same.


The way I've set the system time has always been using SetSystemTime as in the sample here:

http://www.pinvoke.net/default.aspx/kernel32.setsystemtime

Not sure if that solves your problem but maybe worth a try.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜