C++ Date and Time

   This article tries to cover a handful of date and time functions, which can be used in our day to day C++ programming.

C++ Date Time – Using _strdate and _strtime:

The easiest way to program date and time functions is to  use the functions _strdate and _strtime. Both these functions are declared in time.h. These two functions extract the current date and current time respectively.

The following sample program explains their usage. This program prints the current date and current time.


#include <stdio.h>
#include <time.h>

void main( )
{
char dateStr [9];
char timeStr [9];
_strdate( dateStr);
printf( "The current date is %s n", dateStr);
_strtime( timeStr );
printf( "The current time is %s n", timeStr);
}

C++ Date Time – Using SYSTEMTIME and FILETIME:

There are five different formats for date time in windows. They are System Time, File Time, Local time, MS-DOS and Windows(milliseconds since the system rebooted). Among this five, System Time and File Time are used prominently.

SYSTEMTIME is a structure which stores the date and time as Year, Month, Day, hour etc., Its format is as follows.


typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME;

A sample for displaying date and time using SYSTEMTIME is as follows. This program displays the current Coordinated Universal date and Time, using GetSystemTime function.


#include <Windows.h>
#include <stdio.h>

void main()
{
SYSTEMTIME st;
GetSystemTime(&st);
printf("Year:%dnMonth:%dnDate:%dnHour:%dnMin:%dnSecond:% dn" ,st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
}

It is very convenient to use the SYSTEMTIME structure because it contains all the values in a human readable format.

FILETIME structure stores time as number of 100 nanoseconds elapsed since January 1, 1601. So whenever this structure is used, for display purposes this has to be converted to SYSTEMTIME format. The C++ function FileTimeToSystemTime is used to achieve this purpose.