如何在C++中获取当前时间和日期?

Max*_*rai 407 c++ time cross-platform date

有没有一种跨平台的方式来获取C++中的当前日期和时间?

Fre*_*ool 511

在C++ 11中,您可以使用 std::chrono::system_clock::now()

示例(从en.cppreference.com复制):

#include <iostream>
#include <chrono>
#include <ctime>    

int main()
{
    auto start = std::chrono::system_clock::now();
    // Some computation here
    auto end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}
Run Code Online (Sandbox Code Playgroud)

这应该是这样的:

finished computation at Mon Oct  2 00:59:08 2017
elapsed time: 1.88232s
Run Code Online (Sandbox Code Playgroud)

  • 没有使用获得的值的示例,这个答案很少使用.例如,如何打印,获取当地时间,与其他日期/时间进行比较? (59认同)
  • 这是最糟糕的答案.它使其他c ++ 11答案重复,但它没有解释,只是一个"链接". (30认同)
  • 这应该被推崇,因为它是当前C++中最便携和最简单的方法. (23认同)
  • 没有办法比这个答案更能说明问题.OP问:"有没有一种跨平台的方式来获取C++中的当前日期和时间?" 这个问题就是这个问题.如果您对如何从`stream`获取`string`或如何正确格式化`time_point <>`有疑问,请继续询问另一个问题或google之后. (8认同)
  • @Johannes,刚加我的.按照这个速度,这应该是2017年8月15日16:31 UTC的最佳答案:-) (4认同)
  • 如何将`std :: chrono :: system_clock :: now()`的结果更改为string?不是`cout` (3认同)
  • 链接页面上存在示例. (2认同)
  • 为什么没有一些我可以调用的简单函数来捕获当前本地时间,并且成员函数可以让我访问 struct tm 中找到的所有组件以及其他一些字符串转换函数。所有这些电话都是为了获取基本的常见信息,并在此处添加 1900,在那里添加 1。看起来很荒谬。 (2认同)
  • @ThermoX 欢迎使用 C++ (2认同)

小智 464

C++与C共享其日期/时间函数.对于C++程序员来说,tm结构可能是最简单的 - 以下打印今天的日期:

#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";
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你想要一个日期字符串,请使用`ctime()`和这个答案. (24认同)
  • @Petr你不需要解除分配,因为它是静态分配的,请参阅此处的主题http://stackoverflow.com/questions/8694365/how-is-the-result-struct-of-localtime-allocated-in -C (8认同)
  • @Petr你只需要在分配了new的内存上调用delete. (3认同)
  • 好但是你仍然从localtime()获得一个指针,所以结构实例是否在堆上分配?这意味着它不会被清理,除非你以某种方式这样做.我从来没有说过使用`delete`(c ++ keyword),我只是认为它应该以某种方式删除:)或者谁会为你做这个? (3认同)
  • 那么删除`struct tm`的实例怎么可能只调用delete呢? (2认同)
  • @slier 因为 `tm_year` 从 1900 开始计数,并且 `tm_mon` 根据定义具有 [0, 11] 范围。例如,请参阅答案中的链接。 (2认同)

小智 175

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

#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
}
Run Code Online (Sandbox Code Playgroud)

输出:

currentDateTime()=2012-05-06.21:47:59
Run Code Online (Sandbox Code Playgroud)

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

  • 返回类型是"const std :: string",因此它会返回值,然后在释放之前生成缓冲区的副本. (6认同)
  • 为什么返回`const`值?那是无目的的. (3认同)

Mar*_*ork 139

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

time_t  timev;
time(&timev);
Run Code Online (Sandbox Code Playgroud)

  • anon的答案下面有一个更好的结构,并提供了一个更好的例子. (24认同)
  • 此外,他问的是 C++ 而不是 C。 (2认同)
  • @jterm它的确定,C和C++共享完全相同的时间库,它是一个不同的导入名称的问题,就是这样 (2认同)

Vai*_*tle 30

C++标准库不提供正确的日期类型.C++继承了C语言中日期和时间操作的结构和函数,以及考虑本地化的几个日期/时间输入和输出函数.

// Current date/time based on current system
time_t now = time(0);

// Convert now to tm struct for local timezone
tm* localtm = localtime(&now);
cout << "The local date and time is: " << asctime(localtm) << endl;

// Convert now to tm struct for UTC
tm* gmtm = gmtime(&now);
if (gmtm != NULL) {
cout << "The UTC date and time is: " << asctime(gmtm) << endl;
}
else {
cerr << "Failed to get the UTC date and time" << endl;
return EXIT_FAILURE;
}
Run Code Online (Sandbox Code Playgroud)


How*_*ant 22

旧问题的新答案:

问题没有说明在什么时区.有两种合理的可能性:

  1. 在UTC中.
  2. 在计算机的本地时区.

对于1,您可以使用此日期库和以下程序:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    std::cout << system_clock::now() << '\n';
}
Run Code Online (Sandbox Code Playgroud)

这只是输出给我:

2015-08-18 22:08:18.944211
Run Code Online (Sandbox Code Playgroud)

日期库本质上只是添加了一个流操作符std::chrono::system_clock::time_point.它还增加了许多其他不错的功能,但这并没有在这个简单的程序中使用.

如果您更喜欢2(本地时间),则会在日期库之上构建时区.假设编译器支持C++ 11或C++ 14,这两个库都是开源跨平台的.

#include "tz.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto local = make_zoned(current_zone(), system_clock::now());
    std::cout << local << '\n';
}
Run Code Online (Sandbox Code Playgroud)

对我来说只输出:

2015-08-18 18:08:18.944211 EDT
Run Code Online (Sandbox Code Playgroud)

从结果类型make_zoneddate::zoned_time其的一个配对date::time_zone和一个std::chrono::system_clock::time_point.此对代表本地时间,但也可以表示UTC,具体取决于您查询它的方式.

有了上面的输出,你可以看到,我的电脑是目前与UTC -4H的偏移和EDT的缩写时区.

如果需要其他时区,也可以完成.例如,要查找悉尼当前时间,澳大利亚只需将变量的构造更改local为:

auto local = make_zoned("Australia/Sydney", system_clock::now());
Run Code Online (Sandbox Code Playgroud)

输出变为:

2015-08-19 08:08:18.944211 AEST
Run Code Online (Sandbox Code Playgroud)


Off*_*rmo 18

(对于谷歌同行)

还有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();
Run Code Online (Sandbox Code Playgroud)


小智 14

#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;
} 
Run Code Online (Sandbox Code Playgroud)


Roi*_*ton 14

auto time = std::time(nullptr);
std::cout << std::put_time(std::localtime(&time), "%F %T%z"); // ISO 8601 format.
Run Code Online (Sandbox Code Playgroud)

使用std::time()std::chrono::system_clock::now()(或其他时钟类型)获取当前时间.

std::put_time()(C++ 11)和strftime()(C)提供了很多格式化程序来输出那些时间.

#include <iomanip>
#include <iostream>

int main() {
    auto time = std::time(nullptr);
    std::cout
        // ISO 8601: %Y-%m-%d %H:%M:%S, e.g. 2017-07-31 00:42:00+0200.
        << std::put_time(std::gmtime(&time), "%F %T%z") << '\n'
        // %m/%d/%y, e.g. 07/31/17
        << std::put_time(std::gmtime(&time), "%D"); 
}
Run Code Online (Sandbox Code Playgroud)

格式化程序的顺序很重要:

std::cout << std::put_time(std::gmtime(&time), "%c %A %Z") << std::endl;
// Mon Jul 31 00:00:42 2017 Monday GMT
std::cout << std::put_time(std::gmtime(&time), "%Z %c %A") << std::endl;
// GMT Mon Jul 31 00:00:42 2017 Monday
Run Code Online (Sandbox Code Playgroud)

格式化程序strftime()类似:

char output[100];
if (std::strftime(output, sizeof(output), "%F", std::gmtime(&time))) {
    std::cout << output << '\n'; // %Y-%m-%d, e.g. 2017-07-31
}
Run Code Online (Sandbox Code Playgroud)

通常,大写格式化程序表示"完整版本",小写表示缩写(例如Y:2017,y:17).


区域设置会改变输出:

#include <iomanip>
#include <iostream>
int main() {
    auto time = std::time(nullptr);
    std::cout << "undef: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("en_US.utf8"));
    std::cout << "en_US: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("en_GB.utf8"));
    std::cout << "en_GB: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("de_DE.utf8"));
    std::cout << "de_DE: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("ja_JP.utf8"));
    std::cout << "ja_JP: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("ru_RU.utf8"));
    std::cout << "ru_RU: " << std::put_time(std::gmtime(&time), "%c");        
}
Run Code Online (Sandbox Code Playgroud)

可能的输出(Coliru,Compiler Explorer):

undef: Tue Aug  1 08:29:30 2017
en_US: Tue 01 Aug 2017 08:29:30 AM GMT
en_GB: Tue 01 Aug 2017 08:29:30 GMT
de_DE: Di 01 Aug 2017 08:29:30 GMT
ja_JP: 2017?08?01? 08?29?30?
ru_RU: ?? 01 ??? 2017 08:29:30
Run Code Online (Sandbox Code Playgroud)

我用于std::gmtime()转换为UTC.std::localtime()提供转换为当地时间.

注意asctime()/ ctime()在其他答案中提到的/ 现在被标记为已弃用,strftime()应该是首选.


0x4*_*2D2 12

是的,您可以使用当前使用的区域设置指定的格式规则来执行此操作:

#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");
}
Run Code Online (Sandbox Code Playgroud)

输出: Fri Sep 6 20:33:31 2013

  • 恕我直言,这实际上是最好的答案,因为它是唯一尊重区域设置的答案,并且因为它的编程非常注重细节(您不会经常看到“ostream::sentry”)。 (2认同)

Sam*_*dul 7

你可以使用C++ 11时间类:

    #include <iostream>
    #include <iomanip>
    using namespace std;

    int main() {

       time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());
       cout << put_time(localtime(&now), "%F %T") <<  endl;
      return 0;
     }
Run Code Online (Sandbox Code Playgroud)

出局:

2017-08-25 12:30:08
Run Code Online (Sandbox Code Playgroud)


Jam*_*ert 6

总有__TIMESTAMP__预处理器宏.

#include <iostream>

using namespace std

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

int main() {
    printBuildDateTime();
}
Run Code Online (Sandbox Code Playgroud)

例如:2014年4月13日星期日11:28:08

  • 这不起作用,因为__TIMESTAMP__将给出创建文件的时间而不是当前时间. (26认同)
  • 回顾这一点,我不知道为什么我感到有能力回答C ++问题 (2认同)

Mar*_*hke 6

std::ctime

为什么到目前为止评论中只提到了ctime ?

#include <ctime>
#include <iostream>
 
int main()
{
    std::time_t result = std::time(nullptr);
    std::cout << std::ctime(&result);
}
Run Code Online (Sandbox Code Playgroud)

输出

Tue Dec 27 17:21:29 2011


Joh*_*ohn 5

您可以使用以下代码C++ 中获取当前系统日期时间

    #include <iostream>
    #include <time.h> //It may be #include <ctime> or any other header file depending upon
                     // compiler or IDE you're using 
    using namespace std;

    int main() {
       // current date/time based on current system
       time_t now = time(0);

       // convert now to string form
       string dt = ctime(&now);

       cout << "The local date and time is: " << dt << endl;
    return 0;
    }
Run Code Online (Sandbox Code Playgroud)

PS: 访问站点以获取更多信息。