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

时间:2009-06-15 19:35:39

标签: c++ date time cross-platform

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

24 个答案:

答案 0 :(得分:466)

在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";
}

这应该是这样的:

finished computation at Mon Oct  2 00:59:08 2017
elapsed time: 1.88232s

答案 1 :(得分:456)

C ++与C共享其日期/时间函数。tm structure可能是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";
}

答案 2 :(得分:170)

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

#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

有关日期/时间格式的详情,请访问here

答案 3 :(得分:139)

std C库提供time()。 这是纪元的秒数​​,可以使用标准C函数转换为日期和H:M:S提升也有a time/date library,您可以查看。

time_t  timev;
time(&timev);

答案 4 :(得分: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;
}

答案 5 :(得分:21)

旧问题的新答案:

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

  1. 在UTC中。
  2. 在计算机的本地时区。
  3. 对于1,您可以使用this date library和以下程序:

    #include "date.h"
    #include <iostream>
    
    int
    main()
    {
        using namespace date;
        using namespace std::chrono;
        std::cout << system_clock::now() << '\n';
    }
    

    哪个只为我输出:

    2015-08-18 22:08:18.944211
    

    日期库基本上只是为std::chrono::system_clock::time_point添加了一个流媒体运算符。它还增加了许多其他不错的功能,但在这个简单的程序中没有使用它。

    如果您更喜欢2(当地时间),则timezone library会建立在date library之上。假设编译器支持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';
    }
    

    对我来说只输出:

    2015-08-18 18:08:18.944211 EDT
    

    make_zoned的结果类型是date::zoned_time,它是date::time_zonestd::chrono::system_clock::time_point的配对。该对代表当地时间,但也可以代表UTC,具体取决于您查询它的方式。

    通过上面的输出,您可以看到我的计算机当前处于UTC偏移为-4h的时区,缩写为EDT。

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

    auto local = make_zoned("Australia/Sydney", system_clock::now());
    

    输出变为:

    2015-08-19 08:08:18.944211 AEST
    

答案 6 :(得分: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();

答案 7 :(得分: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;
} 

答案 8 :(得分:13)

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

使用std::time()std::chrono::system_clock::now()(或其他clock type)获取当前时间。

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"); 
}

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

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

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
}

通常,资本格式化程序意味着&#34;完整版本&#34;小写表示缩写(例如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");        
}

可能的输出(ColiruCompiler 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

我已使用std::gmtime()转换为UTC。提供std::localtime()以转换为当地时间。

注意其他答案中提及的asctime() / ctime()现已标记为已弃用,strftime()应首选。

答案 9 :(得分: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");
}
  

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

答案 10 :(得分: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;
     }

out put:

2017-08-25 12:30:08

答案 11 :(得分:6)

始终是__TIMESTAMP__预处理器宏。

#include <iostream>

using namespace std

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

int main() {
    printBuildDateTime();
}

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

答案 12 :(得分:4)

您也可以直接使用ctime()

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

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

  time ( &rawtime );
  printf ( "Current local time and date: %s", ctime (&rawtime) );

  return 0;
} 

答案 13 :(得分:4)

我发现此链接对我的实现非常有用: C++ Date and Time

这是我在实施中使用的代码,以获得明确的&#34; YYYYMMDD HHMMSS&#34;输出格式。该参数用于在UTC和本地时间之间切换。您可以轻松修改我的代码以满足您的需求。

#include <iostream>
#include <ctime>

using namespace std;

/**
 * This function gets the current date time
 * @param useLocalTime true if want to use local time, default to false (UTC)
 * @return current datetime in the format of "YYYYMMDD HHMMSS"
 */

string getCurrentDateTime(bool useLocalTime) {
    stringstream currentDateTime;
    // current date/time based on current system
    time_t ttNow = time(0);
    tm * ptmNow;

    if (useLocalTime)
        ptmNow = localtime(&ttNow);
    else
        ptmNow = gmtime(&ttNow);

    currentDateTime << 1900 + ptmNow->tm_year;

    //month
    if (ptmNow->tm_mon < 9)
        //Fill in the leading 0 if less than 10
        currentDateTime << "0" << 1 + ptmNow->tm_mon;
    else
        currentDateTime << (1 + ptmNow->tm_mon);

    //day
    if (ptmNow->tm_mday < 10)
        currentDateTime << "0" << ptmNow->tm_mday << " ";
    else
        currentDateTime <<  ptmNow->tm_mday << " ";

    //hour
    if (ptmNow->tm_hour < 10)
        currentDateTime << "0" << ptmNow->tm_hour;
    else
        currentDateTime << ptmNow->tm_hour;

    //min
    if (ptmNow->tm_min < 10)
        currentDateTime << "0" << ptmNow->tm_min;
    else
        currentDateTime << ptmNow->tm_min;

    //sec
    if (ptmNow->tm_sec < 10)
        currentDateTime << "0" << ptmNow->tm_sec;
    else
        currentDateTime << ptmNow->tm_sec;


    return currentDateTime.str();
}

输出(UTC,EST):

20161123 000454
20161122 190454

答案 14 :(得分:3)

这是针对我在Linux(RHEL)和Windows(x64)上为g ++和OpenMP编写的:

#include <ctime>
#include <iostream>
#include <string>
#include <locale>

////////////////////////////////////////////////////////////////////////////////
//
//  Reports a time-stamped update to the console; format is:
//       Name: Update: Year-Month-Day_of_Month Hour:Minute:Second
//
////////////////////////////////////////////////////////////////////////////////
//
//  [string] strName  :  name of the update object
//  [string] strUpdate:  update descripton
//          
////////////////////////////////////////////////////////////////////////////////

void ReportTimeStamp(string strName, string strUpdate)
{
    try
    {
        #ifdef _WIN64
            //  Current time
            const time_t tStart = time(0);
            //  Current time structure
            struct tm tmStart;

            localtime_s(&tmStart, &tStart);

            //  Report
            cout << strName << ": " << strUpdate << ": " << (1900 + tmStart.tm_year) << "-" << tmStart.tm_mon << "-" << tmStart.tm_mday << " " << tmStart.tm_hour << ":" << tmStart.tm_min << ":" << tmStart.tm_sec << "\n\n";
        #else
            //  Current time
            const time_t tStart = time(0);
            //  Current time structure
            struct tm* tmStart;

            tmStart = localtime(&tStart);

            //  Report
            cout << strName << ": " << strUpdate << ": " << (1900 + tmStart->tm_year) << "-" << tmStart->tm_mon << "-" << tmStart->tm_mday << " " << tmStart->tm_hour << ":" << tmStart->tm_min << ":" << tmStart->tm_sec << "\n\n";
        #endif

    }
    catch (exception ex)
    {
        cout << "ERROR [ReportTimeStamp] Exception Code:  " << ex.what() << "\n";
    }

    return;
}

答案 15 :(得分:2)

这适用于G ++我不确定这是否对你有帮助。 节目输出:

The current time is 11:43:41 am
The current date is 6-18-2015 June Wednesday 
Day of month is 17 and the Month of year is 6,
also the day of year is 167 & our Weekday is 3.
The current year is 2015.

代码:

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

using namespace std;

const std::string currentTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%H:%M:%S %P", &tstruct);
return buf;
}

const std::string currentDate() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%B %A ", &tstruct);
return buf;
}

int main() {
    cout << "\033[2J\033[1;1H"; 
std:cout << "The current time is " << currentTime() << std::endl;
    time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );
    cout << "The current date is " << now->tm_mon + 1 << '-' 
         << (now->tm_mday  + 1) << '-'
         <<  (now->tm_year + 1900) 
         << " " << currentDate() << endl; 

 cout << "Day of month is " << (now->tm_mday) 
      << " and the Month of year is " << (now->tm_mon)+1 << "," << endl;
    cout << "also the day of year is " << (now->tm_yday) 
         << " & our Weekday is " << (now->tm_wday) << "." << endl;
    cout << "The current year is " << (now->tm_year)+1900 << "." 
         << endl;
 return 0;  
}

答案 16 :(得分:2)

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

这种内置似乎提供了一套合理的选择。

答案 17 :(得分:2)

ffead-cpp为各种任务提供了多个实用程序类,其中一个类是Date类,它提供了从Date操作到日期算术的许多功能,还有一个{ {3}}类提供了计时操作。你可以看一下。

答案 18 :(得分:1)

localtime_s()版本:

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

int main ()
{
  time_t current_time;
  struct tm  local_time;

  time ( &current_time );
  localtime_s(&local_time, &current_time);

  int Year   = local_time.tm_year + 1900;
  int Month  = local_time.tm_mon + 1;
  int Day    = local_time.tm_mday;

  int Hour   = local_time.tm_hour;
  int Min    = local_time.tm_min;
  int Sec    = local_time.tm_sec;

  return 0;
} 

答案 19 :(得分:1)

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

<?php

// Create connection
$conn = new mysqli('localhost', 'username', 'pass', 'database');
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM homepage_colors";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $nav_color = $row['nav_color'];
    }
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<body>
<nav style="color: <?php echo $nav_color; ?>"></nav>
</body>
</html>

PS:Visit此站点以获取更多信息。

答案 20 :(得分:0)

您可以使用boost

#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
using namespace boost::gregorian;

int main()
{
    date d = day_clock::universal_day();
    std::cout << d.day() << " " << d.month() << " " << d.year();
}

答案 21 :(得分:0)

#include <Windows.h>

void main()
{
     //Following is a structure to store date / time

SYSTEMTIME SystemTime, LocalTime;

    //To get the local time

int loctime = GetLocalTime(&LocalTime);

    //To get the system time

int systime = GetSystemTime(&SystemTime)

}

答案 22 :(得分:0)

#include <iostream>
#include <chrono>
#include <string>
#pragma warning(disable: 4996)
// Ver: C++ 17 
// IDE: Visual Studio
int main() {
    using namespace std; 
    using namespace chrono;
    time_point tp = system_clock::now();
    time_t tt = system_clock::to_time_t(tp);
    cout << "Current time: " << ctime(&tt) << endl;
    return 0;
}

答案 23 :(得分:0)

std :: ctime

到目前为止,为什么只在评论中提到ctime

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

输出

Tue Dec 27 17:21:29 2011