asctime ()- 将时间转换为字符串

格式

#include <time.h>
char *asctime(const struct tm *time);

语言级别

ANSI

线程安全

False

请改为使用 asctime_r()

描述

asctime() 函数将存储为 time指向的结构的时间转换为字符串。 您可以从对 gmtime()gmtime64()localtime()localtime64() 函数的调用中获取 time 值。

asctime() 生成的字符串结果正好包含 26 个字符,并且具有以下格式:
   "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n"
以下是返回的字符串的示例:
   Sat Jul 16 02:03:55 1994\n\0
or
   Sat Jul 16  2:03:55 1994\n\0

asctime() 函数使用 24 小时制格式。 这些日子缩写为: SunMonTueWedThuFriSat。 月份缩写为: JanFebMarAprMayJunJulAugSepOctNovDec。 所有字段都具有恒定宽度。 只有一个数字的日期前面有零或空格。 换行符 (\n) 和空字符 (\0) 占据字符串的最后两个位置。

时间和日期函数从全球时间 00:00:00 开始, 1970 年 1 月 1。

返回值

asctime() 函数返回指向生成的字符串的指针。 如果该函数不成功,那么它将返回 NULL。
注: asctime()ctime() 函数和其他时间函数可以使用公共的静态分配缓冲区来保存返回字符串。 对其中一个函数的每个调用都可能破坏先前调用的结果。 asctime_r()ctime_r()gmtime_r()localtime_r() 函数不使用公共的静态分配缓冲区来保存返回字符串。 如果需要重新环境,那么可以使用这些函数来代替 asctime()ctime()gmtime()localtime() 函数。

示例

此示例轮询系统时钟并打印给出当前时间的消息。
#include <time.h>
#include <stdio.h>
 
int main(void)
{
    struct tm *newtime;
    time_t ltime;
 
/* Get the time in seconds */
    time(&ltime);
/* Convert it to the structure tm */
    newtime = localtime(&ltime);
 
        /* Print the local time as a string */
    printf("The current date and time are %s",
             asctime(newtime));
}
 
/****************  Output should be similar to:  ******************
The current date and time are Fri Sep 16 13:29:51 1994
*/

相关信息