Monday 28 November 2011

How do you get the date and time in a Windows program? in C programming

How do you get the date and time in a Windows program?

To get the date and time in a Windows program, you should call the standard C library functions time() and localtime() or some derivative (asctime(), ctime(), _ftime(), gmttime()). These functions are compatible with both DOS and Windows. You should never attempt to call a DOS-only or a ROM BIOSfunction directly. You should always use either Windows API function calls or standard C library routines. Here is an example of code that can be used to print the current date and time in a Windows program:

char* szAmPm = “PM”;
char szCurrTime[128];
char szCurrDate[128];
struct tm* tmToday;
time_t lTime;
time(&lTime);
tmToday = localtime(lTime);
wsprintf(szCurrDate, “Current Date: %02d/%02d/%02d”,
tmToday->tm_month, tmToday->tm_mday,
tmToday->tm_year);
if (tmToday->tm_hour < 12 )
strcpy(szAmPm, “AM” );
if (tmToday->tm_hour > 12 )
tmToday->tm_hour -= 12;
wsprintf(szCurrTime, “Current Time: %02d:%02d:%02d %s”,
tmToday->tm_hour, tmToday->tm_min,
tmToday->tm_sec, szAmPm);
TextOut(50, 50, szCurrDate, strlen(szCurrDate));
TextOut(200, 50, szCurrTime, strlen(szCurrTime));
}

The time() and localtime() functions are used to get the current local time (according to the Windows timer, which gets its time from MS-DOS). The time() function returns a time_t variable, and the localtime() function returns a tm structure. The tm structure can easily be used to put the current date and time into a readable format. After this task is completed, the wsprintf() function is used to format the date and time into two strings, szCurrDate and szCurrTime, which are then printed in the current window via  the TextOut() Windows API function call.

Cross Reference:

None.

No comments:

Post a Comment