c++ - 当前日期和时间作为字符串

标签 c++ string date datetime time

我编写了一个函数来获取当前日期和时间,格式为:DD-MM-YYYY HH:MM:SS。它有效,但可以说,它非常丑陋。我怎样才能做到完全相同的事情但更简单?

string currentDateToString()
{
    time_t now = time(0);
    tm *ltm = localtime(&now);

    string dateString = "", tmp = "";
    tmp = numToString(ltm->tm_mday);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;
    dateString += "-";
    tmp = numToString(1 + ltm->tm_mon);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;
    dateString += "-";
    tmp = numToString(1900 + ltm->tm_year);
    dateString += tmp;
    dateString += " ";
    tmp = numToString(ltm->tm_hour);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;
    dateString += ":";
    tmp = numToString(1 + ltm->tm_min);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;
    dateString += ":";
    tmp = numToString(1 + ltm->tm_sec);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;

    return dateString;
}

最佳答案

从 C++11 开始,您可以使用 std::put_time来自 iomanip标题:

#include <iostream>
#include <iomanip>
#include <ctime>

int main()
{
    auto t = std::time(nullptr);
    auto tm = *std::localtime(&t);
    std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
}

std::put_time是一个流操纵器,因此它可以与 std::ostringstream 一起使用为了将日期转换为字符串:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>

int main()
{
    auto t = std::time(nullptr);
    auto tm = *std::localtime(&t);

    std::ostringstream oss;
    oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S");
    auto str = oss.str();

    std::cout << str << std::endl;
}

关于c++ - 当前日期和时间作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16357999/

相关文章:

C++ 计算事件的概率

c++ - 使用std::sort对C风格的2D数组进行部分排序

java - 如何匹配字符串中的1个字符

string - 如何在现代 Delphi 中将 AnsiString 转换为整数?

javascript - 验证日期是否早于当前日期

date - Symfony2/Doctrine "app/console doctrine:schema:update --force"带来一个 ContextErrorException

javascript - 如何检测 Angular2 中 Date 对象的变化?

c++ - 如何创建用户定义大小但没有预定义值的 vector ?

字符串、列表、 vector 的默认构造函数的 C++ 成本

javascript - 如何从 JQuery AJAX 调用返回多个值?