Keep in touch

you can keep in touch with my all blogs and sites by install this Toolbar...
http://rworldtoolbar.ourtoolbar.com/

Saturday, October 18, 2008

Get And Set The System Date And Time using c#

Have you want to get your current system date and time as well as set the system date and time using c# code.
here it is, 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. namespace Sample
  8. {
  9. public partial class Form1 : Form
  10. {
  11. public Form1()
  12. {
  13. InitializeComponent();
  14. }
  15. public struct SystemTime
  16. {
  17. public ushort Year;
  18. public ushort Month;
  19. public ushort DayOfWeek;
  20. public ushort Day;
  21. public ushort Hour;
  22. public ushort Minute;
  23. public ushort Second;
  24. public ushort Millisecond;
  25. };
  26. [DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
  27. public extern static void Win32GetSystemTime(ref SystemTime sysTime);
  28. [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
  29. public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
  30. private void button1_Click(object sender, EventArgs e)
  31. {
  32. // Set system date and time
  33. SystemTime updatedTime = new SystemTime();
  34. updatedTime.Year = (ushort)2008;
  35. updatedTime.Month = (ushort)4;
  36. updatedTime.Day = (ushort)23;
  37. // UTC time; it will be modified according to the regional settings of the target computer so the actual hour might differ
  38. updatedTime.Hour = (ushort)10;
  39. updatedTime.Minute = (ushort)0;
  40. updatedTime.Second = (ushort)0;
  41. // Call the unmanaged function that sets the new date and time instantly
  42. Win32SetSystemTime(ref updatedTime);
  43. // Retrieve the current system date and time
  44. SystemTime currTime = new SystemTime();
  45. Win32GetSystemTime(ref currTime);
  46. // You can now use the struct to retrieve the date and time
  47. MessageBox.Show("It's " + currTime.Hour + " o'clock. Do you know where your C# code is?");
  48. }
  49. }
  50. }
Happy Coding..!!

No comments: