Get And Set The System Date And Time

Get And Set The System Date And Time
C# code snippet that uses unmanaged code to retrieve the current date and time of the Windows operating system, and also sets it to the specified values.
1. using System;
2. using System.Collections.Generic;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Windows.Forms;
6. using System.Runtime.InteropServices;
7. 
8. namespace Sample
9. {
10.     public partial class Form1 : Form
11.     {
12.         public Form1()
13.         {
14.             InitializeComponent();
15.         }
16. 
17.         public struct SystemTime
18.         {
19.             public ushort Year;
20.             public ushort Month;
21.             public ushort DayOfWeek;
22.             public ushort Day;
23.             public ushort Hour;
24.             public ushort Minute;
25.             public ushort Second;
26.             public ushort Millisecond;
27.         };
28. 
29.         [DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
30.         public extern static void Win32GetSystemTime(ref SystemTime sysTime);
31.  
32.         [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
33.         public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
34. 
35.         private void button1_Click(object sender, EventArgs e)
36.         {
37.             // Set system date and time
38.             SystemTime updatedTime = new SystemTime();
39.             updatedTime.Year = (ushort)2008;
40.             updatedTime.Month = (ushort)4;
41.             updatedTime.Day = (ushort)23;
42.             // UTC time; it will be modified according to the regional settings of the target computer so the actual hour might differ
43.             updatedTime.Hour = (ushort)10;
44.             updatedTime.Minute = (ushort)0;
45.             updatedTime.Second = (ushort)0;
46.             // Call the unmanaged function that sets the new date and time instantly
47.             Win32SetSystemTime(ref updatedTime);
48. 
49.             // Retrieve the current system date and time
50.             SystemTime currTime = new SystemTime();
51.             Win32GetSystemTime(ref currTime);
52.             // You can now use the struct to retrieve the date and time
53.             MessageBox.Show("It's " + currTime.Hour + " o'clock. Do you know where your C# code is?");
54.         }
55.     }
56. }
57. 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top