¿Cómo obtener la hora y la fecha actuales en C++?


¿Hay una forma multiplataforma de obtener la fecha y hora actuales en C++?

Author: jackyalcine, 2009-06-15

22 answers

En C++ 11 se puede utilizar std::chrono::system_clock::now()

 390
Author: Frederick The Fool,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-09 07:07:13

C++ comparte sus funciones de fecha / hora con C. La estructura tm es probablemente la más fácil para un programador de C++ para trabajar - la siguiente imprime la fecha de hoy:

#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";
}
 440
Author: milleniumbug,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-21 22:24:24

Puede probar el siguiente código multiplataforma para obtener la fecha/hora actual:

#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
}

Salida:

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

Visite aquí para obtener más información sobre el formato de fecha/hora

 161
Author: TrungTN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-12 06:35:20

Las bibliotecas Std C proporcionan time(). Esto es segundos de la época y se puede convertir a la fecha y H:M:S utilizando funciones C estándar. Boost también tiene una biblioteca de hora/fecha que puede verificar.

time_t  timev;
time(&timev);
 138
Author: Martin York,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-01 17:40:14

La biblioteca estándar de C++ no proporciona un tipo de fecha adecuado. C++ hereda las estructuras y funciones para la manipulación de fecha y hora de C, junto con un par de funciones de entrada y salida de fecha/hora que tienen en cuenta la localización.

// 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;
}
 30
Author: Vaibhav Patle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-13 19:35:32

Nueva respuesta para una vieja pregunta:

La pregunta no especifica en qué zona horaria. Hay dos posibilidades razonables:

  1. En UTC.
  2. En la zona horaria local del equipo.

Para 1, puede usar esta biblioteca de fechas y el siguiente programa:

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

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

Que acaba de salir para mí:

2015-08-18 22:08:18.944211

La biblioteca de fechas esencialmente solo agrega un operador de streaming para std::chrono::system_clock::time_point. También agrega una gran cantidad de otras funciones agradables, pero eso no se usa en este simple programa.

Si prefiere 2 (la hora local), hay una biblioteca de zonas horarias que se construye sobre la biblioteca de fechas . Ambas bibliotecas son open sourcey multiplataforma, asumiendo que el compilador soporta C++11 o 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';
}

Que para mí solo la salida:

2015-08-18 18:08:18.944211 EDT

El tipo de resultado de make_zoned es a date::zoned_time que es un emparejamiento de un date::time_zone y a std::chrono::system_clock::time_point. Este par representa una hora local, pero también puede representar UTC, dependiendo de cómo lo consulta.

Con la salida anterior, puede ver que mi computadora está actualmente en una zona horaria con un desplazamiento UTC de-4h, y una abreviatura de EDT.

Si se desea alguna otra zona horaria, eso también se puede lograr. Por ejemplo , para encontrar la hora actual en Sydney, Australia, simplemente cambie la construcción de la variable local a:

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

Y la salida cambia a:

2015-08-19 08:08:18.944211 AEST
 20
Author: Howard Hinnant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-30 02:11:05

(Para compañeros de Google)

También hay 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();
 17
Author: Offirmo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-20 13:18:41
#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;
} 
 14
Author: etcheve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-26 11:02:24

Sí y puede hacerlo con las reglas de formato especificadas por la configuración regional actualmente imbuida:

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

Salida: Fri Sep 6 20:33:31 2013

 11
Author: 0x499602D2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-11 20:27:00
auto time = std::time(nullptr);
std::cout << std::put_time(std::localtime(&time), "%F %T%z"); // ISO 8601 format.

Obtenga la hora actual usando std::time() o std::chrono::system_clock::now() (u otro tipo de reloj ).

std::put_time() (C++11) y strftime() (C) ofrecer una gran cantidad de formateadores para la salida de esos tiempos.

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

La secuencia de los formateadores importa:

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

Los formateadores de strftime() son similares:

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
}

A menudo, el formateador mayúscula significa "versión completa" y minúscula significa abreviatura (por ejemplo, Y: 2017, y: 17).


La configuración regional altera la salida:

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

Posible salida ( Coliru, Explorador de Compiladores):

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

He utilizado std::gmtime() para la conversión a UTC. std::localtime() se proporciona para convertir a la hora local.

Prestar atención a que asctime()/ctime() que fueron mencionados en otras respuestas están marcados como obsoletos ahora y strftime() debe ser preferido.

 9
Author: Roi Danton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-11 09:15:53

Siempre está la macro del preprocesador __TIMESTAMP__.

#include <iostream>

using namespace std

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

int main() {
    printBuildDateTime();
}

Ejemplo: Sun Apr 13 11:28:08 2014

 5
Author: James Robert Albert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-13 18:31:39

Podría usar la clase de tiempo 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
 5
Author: Sam Abdul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-24 00:29:27

También puedes usar directamente 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;
} 
 4
Author: Abhishek Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-26 16:54:40

Encontré este enlace bastante útil para mi implementación: C++ Fecha y hora

Aquí está el código que uso en mi implementación, para obtener un formato de salida claro "AAAAMMDD HHMMSS". El parámetro in es para cambiar entre UTC y hora local. Puede modificar fácilmente mi código para satisfacer sus necesidades.

#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();
}

Salida (UTC, EST):

20161123 000454
20161122 190454
 4
Author: Joe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-10 15:22:08

Esto compilado para mí en Linux (RHEL) y Windows (x64) dirigido a g++ y 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;
}
 3
Author: Epsilon3,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-21 17:22:09

El ffead-cpp proporciona múltiples clases de utilidad para varias tareas, una de ellas es la clase Date que proporciona una gran cantidad de características desde las operaciones de fecha hasta la aritmética de fecha, también hay una clase Timer para las operaciones de sincronización. Puedes echar un vistazo a lo mismo.

 2
Author: user775757,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-28 03:24:44

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

Este accesorio parece ofrecer un conjunto razonable de opciones.

 2
Author: bduhbya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-07 17:35:28

Esto funciona con G++ No estoy seguro de si esto te ayuda. Salida del programa:

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.

Código:

#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;  
}
 2
Author: Anonymous,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-20 06:54:24
#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)

}
 1
Author: user3414278,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-20 03:07:42

Localtime_s () version:

#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;
} 
 1
Author: sailfish009,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-01 09:11:17

Usted podría utilizar 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();
}
 0
Author: Andreas DM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-08 16:35:21

Puede usar el siguiente código para obtener la fecha y hora del sistema actual en 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;
}

PD: Visite este sitio para obtener más información.

 0
Author: John,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-11 12:46:42