How to get and set Date and Time

11 02 2012

Sometimes we may really need to set/get date and time values to/from system. So whenever we think about to change these parameters generally we should think about time zones and daylight savings time, because most of the time our applications need to run globally in a safe manner.

The time related functions can return time in different formats. The below two are the commonly used formats.

1) System timeUTC based time (Coordinated Universal Time)
2) Local Time – Time based on local time zone

Win32 API provides different functions to set/get System Time and Local Time separately.
GetSystemTime/SetSystemTime – To set or retrieve current system date and time. This is expressed in UTC.
GetLocalTime/SetLocalTime – To set or retrieve current local date and time.

These all functions are using a pointer to a SYSTEMTIME structure as a parameter to receive or contains the current or new system date and time respectively.

void GetTime()
{
	SYSTEMTIME st, lt;

	GetSystemTime(&st);
	GetLocalTime(<);

	CString strSystemTime, strLocalTime;

	strSystemTime.Format( _T("Year = %04d Month = %02d Day = %02d Hour = %02d Min = %02d"),
		st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute);

	strLocalTime.Format( _T("Year = %04d Month = %02d Day = %02d Hour = %02d Min = %02d"),
		lt.wYear, lt.wMonth, lt.wDay, lt.wHour, lt.wMinute);

	AfxMessageBox(_T("SystemTime : " + strSystemTime + "\n") + "LocalTime : " + strLocalTime);
}

The MFC framework simplified the working with times by introducing two wrapper classes, the CTime and COleDatetime classes.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: