Chinaunix

标题: 如何只用标准C++、在一行代码里输出当前时间?最好还能指定格式 [打印本页]

作者: csoapy    时间: 2012-06-12 10:45
标题: 如何只用标准C++、在一行代码里输出当前时间?最好还能指定格式
如题。
我用std:fstream来打日志的,只用标准库里面的函数,所以要求一行,方便些。
作者: sonicling    时间: 2012-06-12 11:15
本帖最后由 sonicling 于 2012-06-12 11:16 编辑

你这不是哪壶不开提哪壶吗。

非要用stream也行,用setw、setprecision、setfill。

如果date是一个struct或者class,可以自己重载运算符

template<typename OS>
OS &operator << (OS &os, const my_date_type & date)
{
    os << setfill('0') <<  setw(4) << date.year
         << setw(0) << _T('-')  <<  setw(2) << date.month
         << setw(0) << _T('-')  <<  setw(2) << date.day << setw(0);
    return os;
}

my_date_type date;
cout << date;
ofstream fs;
fs << date;
作者: Moon_Bird    时间: 2012-06-12 11:25
回复 1# csoapy
ofstream os;
os <<setfill('0')<< setw(2) << Month << '-' <<setw(2) <<Day << '- ' <<setw(4)<<Year;
输出格式为MM - DD - YYYY

   
作者: csoapy    时间: 2012-06-15 13:25
sonicling 发表于 2012-06-12 11:15
你这不是哪壶不开提哪壶吗。


呵呵。看来这个问题真是无解啊,不做点额外工作,你甭想用一条语句输出当前时间。
作者: p36288    时间: 2014-01-19 18:06
弱弱地说,这样算的么:
output << _strtime((char*)malloc(sizeof(char*))) << " " << _strdate((char*)malloc(sizeof(char*))) << endl;

作者: selfrun    时间: 2014-01-20 15:14
回复 5# p36288


    作死的节奏
作者: myworkstation    时间: 2014-01-20 16:08
回复 1# csoapy

用boost库会很方便:
  1. std::cout<<boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time())<<std::endl;
复制代码
如果不用boost只能会C++11引用的chrono或者使用标准C库:
  1. std::time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  2. std::cout<<std::ctime(&t)<<std::endl;
复制代码
C style:
  1. time_t t = mktime(NULL);
  2. std::cout<<ctime(&t)<<std::endl;
  3.    
复制代码
只有用boost库的时候才能一行代码搞定。或者自己去封装重载了流操作符的时间类。
作者: lin5161678    时间: 2014-01-22 13:56
p36288 发表于 2014-01-19 18:06
弱弱地说,这样算的么:
output << _strtime((char*)malloc(sizeof(char*))) << " " << _strdate((char*)malloc(sizeof(char*))) << endl;

1 准备的缓冲区太小 直接越界
2 无法free
3 代码是错误的 所以当然不算




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2