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


当前回答

总有__TIMESTAMP__预处理器宏。

#include <iostream>

using namespace std

void printBuildDateTime () {
    cout << __TIMESTAMP__ << endl;
}

int main() {
    printBuildDateTime();
}

例:2014年4月13日太阳11:28:08

其他回答

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

time_t  timev;
time(&timev);

(给谷歌人)

还有Boost::date_time:

#include <boost/date_time/posix_time/posix_time.hpp>

boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();

你可以尝试下面的跨平台代码来获取当前的日期/时间:

#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
    // for more information about date/time format
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);

    return buf;
}

int main() {
    std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
    getchar();  // wait for keyboard input
}

输出:

currentDateTime()=2012-05-06.21:47:59

有关日期/时间格式的更多信息,请访问这里

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

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

总有__TIMESTAMP__预处理器宏。

#include <iostream>

using namespace std

void printBuildDateTime () {
    cout << __TIMESTAMP__ << endl;
}

int main() {
    printBuildDateTime();
}

例:2014年4月13日太阳11:28:08