获取当前时间为YYYY-MM-DD-HH-MM-SS字符串 [英] Getting the current time as a YYYY-MM-DD-HH-MM-SS string

查看:1466
本文介绍了获取当前时间为YYYY-MM-DD-HH-MM-SS字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获得一种优雅的方式格式化字符串当前时间为YYYY-MM-DD-HH-MM-SS。我可以从Boost的日期时间库ISO格式的当前时间,但它有其他分隔字符串,这将不适合我(我在文件名中使用此)。
当然,我只需更换分隔字符串,但有一种感觉,有一个与日期时间的格式选项做这个更好的方式。有没有这样一种方式,如果是这样,我该如何使用呢?

I'm trying to get the current time as a "YYYY-MM-DD-HH-MM-SS" formatted string in an elegant way. I can take the current time in ISO format from Boost's "Date Time" library, but it has other delimiting strings which won't work for me (I'm using this in a filename). Of course I can just replace the delimiting strings, but have a feeling that there's a nicer way to do this with date-time's formatting options. Is there such a way, and if so, how can I use it?

推荐答案

使用 的std ::的strftime ,它是标准的C ++。

Use std::strftime, it is standard C++.

#include <cstdio>
#include <ctime>

int main ()
{
    std::time_t rawtime;
    std::tm* timeinfo;
    char buffer [80];

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

    std::strftime(buffer,80,"%Y-%m-%d-%H-%M-%S",timeinfo);
    std::puts(buffer);

    return 0;
}

这篇关于获取当前时间为YYYY-MM-DD-HH-MM-SS字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆