命名空间
变体
操作

asctime, asctime_s

来自 cppreference.cn
< c‎ | chrono
定义于头文件 <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 的星期几的三个字母的英语缩写,为 MonTueWedThuFriSatSun 之一。
  • Mmm - 来自 time_ptr->tm_mon 的月份名称的三个字母的英语缩写,为 JanFebMarAprMayJunJulAugSepOctNovDec 之一。
  • 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 年,则行为未定义。
此函数不支持本地化,并且无法删除换行符。
此函数修改静态存储,并且不是线程安全的。
此函数已弃用,不应在新代码中使用。
(自 C23 起)
2)(1) 相同,不同之处在于消息写入用户提供的存储 buf 中,保证以空字符结尾,并且在运行时检测到以下错误并调用当前安装的 约束处理函数
  • buftime_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) 指向静态空字符结尾的字符串的指针,该字符串保存如上所述的日期和时间的文本表示。该字符串可能在 asctimectime 之间共享,并且可能在每次调用这些函数时被覆盖。
2) 成功时返回零,失败时返回非零值,在这种情况下,buf[0] 设置为零(除非 buf 是空指针或 bufsz 为零或大于 RSIZE_MAX)。

[编辑] 注意

asctime 返回指向静态数据的指针,并且不是线程安全的。POSIX 将此函数标记为过时,并建议使用 strftime 代替。C 标准也建议使用 strftime 代替 asctimeasctime_s,因为 strftime 更灵活且对区域设置敏感。

POSIX 限制未定义行为仅限于当输出字符串长度超过 25 个字符时,当 timeptr->tm_wdaytimeptr->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)); // note implicit trailing '\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 函数 (p: 341-342)
  • C89/C90 标准 (ISO/IEC 9899:1990)
  • 4.12.3.1 asctime 函数

[编辑] 参见

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