The localtime_s(), _localtime64_s() and asctime_s()  C functions 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: Displaying the current date and time

To show: The localtime_s(), _localtime64_s() and asctime_s() C functions



/* This program uses _time64() to get the current time and then uses _localtime64_s() 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 <stdlib.h>

#include <stdio.h>

#include <string.h>

#include <time.h>


int main(void)


struct tm newtime;

char am_pm[] = "AM";

__time64_t long_time;

char timebuf[26];

errno_t err;


// Get time as 64-bit integer.



// Convert to local time.

err = _localtime64_s(&newtime, &long_time);

if (err)


printf("Invalid argument to _localtime64_s.");



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;


// Convert to an ASCII representation.

err = asctime_s(timebuf, 26, &newtime);

if (err)


printf("Invalid argument to asctime_s.");



printf("Current date and time is: %.19s %s\n", timebuf, am_pm);



Output example:


Current date and time is: Sun Dec 17 05:29:52 PM

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index