web 2.0

How to Change System Date Programmatically With C#

Hi,

After a long time without posting, I come back with a useful class in order to change, get or set Local System DateTime.

Here is the code :

   1: public class LocalDateTime
   2: {
   3:     [StructLayout(LayoutKind.Sequential)]
   4:     private struct SYSTEMTIME
   5:     {
   6:         public short wYear;
   7:         public short wMonth;
   8:         public short wDayOfWeek;
   9:         public short wDay;
  10:         public short wHour;
  11:         public short wMinute;
  12:         public short wSecond;
  13:         public short wMilliseconds;
  14:     }
  15:  
  16:     [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
  17:     private static extern bool SetSystemTime(ref SYSTEMTIME st);
  18:  
  19:     [DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
  20:     private extern static void GetSystemTime(ref SYSTEMTIME sysTime);
  21:  
  22:     /// <summary>
  23:     /// Set the Local System DateTime
  24:     /// </summary>
  25:     /// <param name="date"></param>
  26:     public static void SetDateTime(DateTime date)
  27:     {
  28:         SYSTEMTIME st = new SYSTEMTIME();
  29:         st.wYear = (short)date.Year;
  30:         st.wMonth = (short)date.Month;
  31:         st.wDay = (short)date.Day;
  32:         st.wHour = (short)date.Hour;
  33:         st.wMinute = (short)date.Minute;
  34:         st.wSecond = (short)date.Second;
  35:         st.wMilliseconds = (short)date.Millisecond;
  36:  
  37:         SetSystemTime(ref st);
  38:     }
  39:  
  40:     /// <summary>
  41:     /// Get the Local System DateTime
  42:     /// </summary>
  43:     /// <returns></returns>
  44:     public static DateTime GetDateTime()
  45:     {
  46:         SYSTEMTIME st = new SYSTEMTIME();
  47:         GetSystemTime(ref st);
  48:  
  49:         return new DateTime(st.wYear, st.wMonth, st.wDay,
  50:             st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
  51:     }
  52: }

Hope this help’s!



Views(2213)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C#

Comments

Add comment


 

biuquote
Loading



Technorati Profile