Namespaces
Variants

std:: ctime

From cppreference.net
< cpp ‎ | chrono ‎ | c
定义于头文件 <ctime>
char * ctime ( const std:: time_t * time ) ;

将给定的纪元时间转换为本地日历时间,再转换为文本表示形式,如同调用 std:: asctime ( std:: localtime ( time ) ) 。生成的字符串具有以下格式:

Www Mmm dd hh:mm:ss yyyy\n
  • Www - 星期几(取值为 Mon Tue Wed Thu Fri Sat Sun 之一)。
  • Mmm - 月份(取值为 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 之一)。
  • dd - 日期(月内第几天)。
  • hh - 小时。
  • mm - 分钟。
  • ss - 秒。
  • yyyy - 年份。

该函数不支持本地化。

目录

参数

time - 指向 std::time_t 对象的指针,用于指定要打印的时间

返回值

指向静态空终止字符字符串的指针,该字符串包含日期和时间的文本表示形式。该字符串可能在 std::asctime std::ctime 之间共享,并可能在每次调用这些函数时被覆盖。

注释

此函数返回指向静态数据的指针且非线程安全。此外,它会修改静态 std::tm 对象,该对象可能与 std::gmtime std::localtime 共享。POSIX 将此函数标记为过时,并建议改用 std::strftime

对于会导致字符串长度超过25个字符的 std::time_t 值(例如年份10000),其行为可能是未定义的。

示例

#include <cassert>
#include <cstring>
#include <ctime>
#include <iostream>
int main()
{
    std::time_t result = std::time(nullptr);
    std::cout << std::ctime(&result);
    char buffer[32];
    std::strncpy(buffer, std::ctime(&result), 26);
    assert('\n' == buffer[std::strlen(buffer) - 1]);
    std::cout << buffer;
}

可能的输出:

Mon Oct 11 17:10:55 2021
Mon Oct 11 17:10:55 2021

参见

std::tm 对象转换为文本表示形式
(函数)
std::tm 对象转换为自定义文本表示形式
(函数)
(C++11)
根据指定格式格式化并输出日期/时间值
(函数模板)
C 文档 关于 ctime