在c++中是否有跨平台的方法来获取当前的日期和时间?


当前回答

是的,你可以这样做的格式规则指定的当前填充区域:

#include <iostream>
#include <iterator>
#include <string>

class timefmt
{
public:
    timefmt(std::string fmt)
        : format(fmt) { }

    friend std::ostream& operator <<(std::ostream &, timefmt const &);

private:
    std::string format;
};

std::ostream& operator <<(std::ostream& os, timefmt const& mt)
{
    std::ostream::sentry s(os);

    if (s)
    {
        std::time_t t = std::time(0);
        std::tm const* tm = std::localtime(&t);
        std::ostreambuf_iterator<char> out(os);

        std::use_facet<std::time_put<char>>(os.getloc())
            .put(out, os, os.fill(),
                 tm, &mt.format[0], &mt.format[0] + mt.format.size());
    }

    os.width(0);

    return os;
}

int main()
{
    std::cout << timefmt("%c");
}

输出:周五9月6日20:33:31 2013

其他回答

std C库提供time()。 这是从纪元开始的秒数,可以使用标准C函数转换为日期和H:M:S。Boost还有一个时间/日期库供您检查。

time_t  timev;
time(&timev);

http://www.cplusplus.com/reference/ctime/strftime/

这个内置功能似乎提供了一组合理的选项。

我需要一种方法在每次更新列表时插入当前日期-时间。 简单地说,这似乎很有效。

#include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
int main()
{   //initialize variables
    time_t now; 
    //blah..blah
    /*each time I want the updated stamp*/
    now=time(0);cout<<ctime(&now)<<"blah_blah";
}

c++与C共享它的日期/时间函数。tm结构可能是c++程序员最容易使用的结构——下面打印今天的日期:

#include <ctime>
#include <iostream>

int main() {
    std::time_t t = std::time(0);   // get time now
    std::tm* now = std::localtime(&t);
    std::cout << (now->tm_year + 1900) << '-' 
         << (now->tm_mon + 1) << '-'
         <<  now->tm_mday
         << "\n";
}
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );

  return 0;
}