Another localtime(), _localtime64(), _localetime64_s() and asctime_s() C function examples
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Target platform: none, just for learning
Header file: Standard and Windows
Additional library: Windows Platform SDK
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info: non-CLR or unmanaged
To do: Another example of converting date and time
To show: Another localtime(), _localtime64(), _localetime64_s() and asctime_s() C examples
/* This program uses _time64() to get the current time and then uses localtime64() to convert this time to a structure
* representing the local time. The program converts the result from a 24-hour clock to a 12-hour clock and determines the
* proper extension (AM or PM).
*/
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(void)
{
struct tm *newtime;
char am_pm[] = "AM";
__time64_t long_time;
char buff[30];
// Get time as 64-bit integer and convert to local time.
_time64(&long_time);
// Note: _localtime64() deprecated; consider _localetime64_s()
newtime = _localtime64(&long_time); // C4996
if(newtime->tm_hour > 12) // Set up extension.
strcpy_s(am_pm, sizeof(am_pm), "PM");
if(newtime->tm_hour > 12) // Convert from 24-hour
newtime->tm_hour -= 12; // to 12-hour clock.
if(newtime->tm_hour == 0) // Set hour to 12 if midnight.
newtime->tm_hour = 12;
asctime_s(buff, sizeof(buff), newtime);
printf("Current date and time is: %.19s %s\n", buff, am_pm);
}
Output example:
Current date and time is: Sun Dec 17 05:34:59 PM
Press any key to continue . . .