Linux 拨号vps windows公众号手机端

c++中strftime函数怎么使用

lewis 5年前 (2020-04-21) 阅读数 14 #程序编程
文章标签 c++

在C++中,strftime函数用于将时间日期格式化为字符串。其函数原型如下:

size_t strftime(char* str, size_t count, const char* format, const struct tm* timeptr);

参数说明:

  • str:指向存储格式化后字符串的缓冲区
  • count:缓冲区的大小
  • format:格式化字符串的格式
  • timeptr:指向tm结构体的指针,包含要格式化的时间日期信息

示例代码如下:

#include <iostream>
#include <ctime>

int main() {
    char buffer[80];
    const char* format = "%Y-%m-%d %H:%M:%S"; // 日期时间格式
    time_t rawtime;
    struct tm* timeinfo;

    time(&rawtime);
    timeinfo = localtime(&rawtime);

    strftime(buffer, 80, format, timeinfo);

    std::cout << "当前时间为:" << buffer << std::endl;

    return 0;
}

在上面的示例中,我们使用了strftime函数将当前时间格式化为指定的字符串格式并存储在buffer中,然后将其输出到控制台。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门