Namespaces
Variants

asctime, asctime_s

From cppreference.net
定义于头文件 <time.h>
(1)
char * asctime ( const struct tm * time_ptr ) ;
(C23前)
[ [ deprecated ] ] char * asctime ( const struct tm * time_ptr ) ;
(C23起)
errno_t asctime_s ( char * buf, rsize_t bufsz, const struct tm * time_ptr ) ;
(2) (C11起)
1) 将给定的日历时间 tm 转换为以下固定25字符格式的文本表示: Www Mmm dd hh : mm : ss yyyy\n
  • Www - 来自 time_ptr - > tm_wday 的三字母英文星期缩写,取值为 Mon , Tue , Wed , Thu , Fri , Sat , Sun 之一
  • Mmm - 来自 time_ptr - > tm_mon 的三字母英文月份缩写,取值为 Jan , Feb , Mar , Apr , May , Jun , Jul , Aug , Sep , Oct , Nov , Dec 之一
  • dd - 来自 timeptr - > tm_mday 的2位数字日期,如同使用 sprintf 配合 % 2d 格式输出
  • hh - 来自 timeptr - > tm_hour 的2位数字小时,如同使用 sprintf 配合 % .2d 格式输出
  • mm - 来自 timeptr - > tm_min 的2位数字分钟,如同使用 sprintf 配合 % .2d 格式输出
  • ss - 来自 timeptr - > tm_sec 的2位数字秒数,如同使用 sprintf 配合 % .2d 格式输出
  • yyyy - 来自 timeptr - > tm_year + 1900 的4位数字年份,如同使用 sprintf 配合 % 4d 格式输出
如果 * time_ptr 的任何成员超出其正常范围,则行为未定义。
time_ptr - > tm_year 指示的日历年份超过4位数或小于1000年,则行为未定义。
该函数不支持本地化,且无法移除换行符。
该函数修改静态存储且非线程安全。
此函数已被弃用,不应在新代码中使用。
(since C23)
2) (1) 相同,不同之处在于消息被写入用户提供的存储空间 buf (该空间保证以空字符结尾),并在运行时检测以下错误时调用当前安装的 约束处理函数
  • buf time_ptr 是空指针
  • bufsz 小于26或大于 RSIZE_MAX
  • * time_ptr 的成员未全部处于正常取值范围内
  • time_ptr - > tm_year 指示的年份小于0或大于9999
与所有边界检查函数一样,仅当实现定义了 __STDC_LIB_EXT1__ 且用户在包含 <time.h> 前将 __STDC_WANT_LIB_EXT1__ 定义为整型常量 1 时,才保证 asctime_s 可用。

目录

参数

time_ptr - 指向 tm 对象的指针,用于指定要打印的时间
buf - 指向用户提供缓冲区的指针,缓冲区长度至少为26字节
bufsz - 用户提供缓冲区的大小

返回值

1) 指向静态空终止字符字符串的指针,该字符串包含如上所述的日期和时间文本表示。该字符串可能在 asctime ctime 之间共享,并可能在每次调用这些函数时被覆盖。
2) 成功时返回零,失败时返回非零值,此时 buf [ 0 ] 将被置零(除非 buf 为空指针,或 bufsz 为零或大于 RSIZE_MAX )。

注释

asctime 返回指向静态数据的指针且非线程安全。POSIX 将此函数标记为过时并建议改用 strftime 。C 标准同样建议使用 strftime 替代 asctime asctime_s ,因为 strftime 更具灵活性且支持区域设置。

POSIX 仅将未定义行为限制在以下情况:当输出字符串长度超过25个字符时,当 timeptr - > tm_wday timeptr - > tm_mon 超出预期范围时,或当 timeptr - > tm_year 超过 INT_MAX - 1990 时。

某些实现将 timeptr - > tm_mday == 0 处理为表示前一个月的最后一天。

示例

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <time.h>
int main(void)
{
    struct tm tm = *localtime(&(time_t){time(NULL)});
    printf("%s", asctime(&tm)); // 注意隐式尾随的 '\n'
#ifdef __STDC_LIB_EXT1__
    char str[26];
    asctime_s(str, sizeof str, &tm);
    printf("%s", str);
#endif
}

可能的输出:

Tue May 26 21:51:50 2015
Tue May 26 21:51:50 2015

参考文献

  • C17 标准 (ISO/IEC 9899:2018):
  • 7.27.2.1 asctime 函数 (p: 287)
  • K.3.8.2.1 asctime_s 函数 (p: 453-454)
  • C11 标准 (ISO/IEC 9899:2011):
  • 7.27.2.1 asctime 函数 (p: 392-393)
  • K.3.8.2.1 asctime_s 函数 (p: 624-625)
  • C99标准(ISO/IEC 9899:1999):
  • 7.23.3.1 asctime函数(页码:341-342)
  • C89/C90 标准 (ISO/IEC 9899:1990):
  • 4.12.3.1 asctime 函数

参见

(C23中已弃用) (C11)
time_t 对象转换为文本表示形式
(函数)
tm 对象转换为自定义文本表示形式
(函数)
C++ 文档 关于 asctime