C++: How to show system time and date in Windows

Windows local time and date can be obtained from SYSTEMTIME structure using GetLocalTime() function.

The SYSTEMTIME structure has the following members: wYear, wMonth,wDay, wDayOfWeek,wHour, wMinute,wSecond,wMilliseconds. All members are of type WORD.

The GetLocalTime() function has only one parameter. That is-- pointer to SYSTEMTIME structure. When this function is called, it sets the values to corresponding members. Then we can output them.

The following code shows how we can show running system time, date in the console.

#include<iostream> #include<windows.h> using namespace std; main() { loop: system("cls"); SYSTEMTIME st; GetLocalTime(&st); int hr = st.wHour; char* sfx = new char[3]; if (hr>=12) sfx="PM"; else sfx="AM"; if (hr>12) hr -= 12; cout <<"System Time Information"<<endl <<"Date :"<<st.wDay<<"/"<<st.wMonth <<"/"<<st.wYear<<endl <<"Time :"<<hr <<":"<<st.wMinute <<":"<<st.wSecond<<sfx<<endl; Sleep(1000); goto loop; }

No comments:

Post a Comment

Thank you for commenting. Please keep visiting.