How to Use Date and Time in a C++ Program
Dates and times have frequent usage in C++ programs. Windows programs use several different time formats: System time, local time, file time, Windows time and MS-DOS time. The Run Time Library of C++ offers various tools to extract and manipulate time formats easily. They are defined in the time.h header file. This tutorial demonstrates the usage of some formats and tools.
Things You'll Need
- Intermediate level of C++
- C++ compiler with IDE, such as Visual Studio 2008
Instructions
-
-
1
Extract the current date and time using _strdate and _strtime. This is the simplest and one of the most frequently used date-time operations in C++:
#include < iostream.h >
#include < time.h >
void main() {
char sdate[9];
char stime[9];
_strdate( sdate );
_strtime( stime );
cout << "time: " << stime << " date: " << sdate << endl;
} -
2
Understand System time by looking at the fields of the _SYSTEMTIME struct. Note the use of the typedef keyword to define the struct as type SYSTEMTIME:
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME; -
-
3
Display universal time and date using the SYSTEMTIME type and the GetSystemTime function:
#include < iostream.h >
#include < Windows.h >
using namespace std;
int main(){
SYSTEMTIME* p_st = new SYSTEMTIME;
GetSystemTime(p_st);
cout << "Year: " << p_st->wYear << endl;
cout << "Month: " << p_st->wMonth << endl;
cout << "Day: " << p_st->wDate << endl;
cout << "Hour: " << p_st->wHour << endl;
cout << "Minutes: " << p_st->wMinute << endl;
cout << " Seconds: " << p_st->wSeconds << endl;
cout << "Milliseconds: " << p_st->wMilliseconds << endl;
} -
4
Use the function FileTimeToSystemTime to express time as the number of nanoseconds that have elapsed since January 1, 1601. The function writes the result to a FILETIME type and converts it to a human-readable SYSTEMTIME type. Note that this function accepts both types as pointers:
BOOL WINAPI FileTimeToSystemTime(
__in const FILETIME* pFT,
__out SYSTEMTIME* pST
);
-
1