En  Fa
softprojects.org
Discovering: Tips & Tricks  > Languages  > C# Tips  > How to get and set system time in C#
 

Articles

 

 

Tips and Tricks

 


 

How to get and set system time in C#

Print version  

How to get and set system time in C#

Description

With this class you can get or set the system time. This class uses windows API.

C# Code

public class SystemTime
{
	public struct _SYSTEMTIME
	{
		// WORD = UInt16
		public UInt16 wYear;
		public UInt16 wMonth;
		public UInt16 wDayOfWeek;
		public UInt16 wDay;
		public UInt16 wHour;
		public UInt16 wMinute;
		public UInt16 wSecond;
		public UInt16 wMilliseconds;
	}
	[DllImport("Kernel32.dll")]
	public static extern void GetSystemTime(out _SYSTEMTIME lpSystemTime);
	[DllImport("Kernel32.dll")]
	public static extern bool SetSystemTime(ref _SYSTEMTIME lpSystemTime);
	[DllImport("Kernel32.dll")]
	public static extern void GetLocalTime(out _SYSTEMTIME lpSystemTime);

	[DllImport("Kernel32.dll")]
	public static extern bool SetLocalTime(ref _SYSTEMTIME lpSystemTime);

	public static _SYSTEMTIME ConvertToSystemTime(DateTime dt)
	{
		_SYSTEMTIME sysTime = new _SYSTEMTIME();
		sysTime.wYear = Convert.ToUInt16(dt.Year);
		sysTime.wDay = Convert.ToUInt16(dt.Day);
		sysTime.wDayOfWeek = (UInt16)dt.DayOfWeek;
		sysTime.wHour = Convert.ToUInt16(dt.Hour);
		sysTime.wSecond = Convert.ToUInt16(dt.Second);
		sysTime.wMinute = Convert.ToUInt16(dt.Minute);
		sysTime.wMonth = Convert.ToUInt16(dt.Month);
		sysTime.wMilliseconds = Convert.ToUInt16(dt.Millisecond);
		return sysTime;
	}
}
Details
      
Writer: Salar Khalilzadeh
Date Sent: 6/30/2008 8:46 PM
Views: 235
Votes: 5
Rating: 3.80 Points from 3.80 Points

Your Rating:
bookmark this
 

There is no comment for this topic.

Language:

Copyright © 2008 SoftProjects.org | About | Valid XHTML | CSS