2011-12-01 51 views
10

Cómo obtener la fecha actual d/m/y. Necesito que tengan 3 variables diferentes, no una, por ejemplo day=d; month=m; year=y;.¿Cómo obtener la fecha y hora actual?

+1

debe especificar una plataforma. – unwind

+0

¿Qué has probado? http://stackoverflow.com/questions/997946/c-get-current-time-and-date – daniloquio

+0

@Fredrik, es más fácil preguntar que investigar. –

Respuesta

21

Para Linux, usaría la función 'localtime'.

#include <time.h> 

time_t theTime = time(NULL); 
struct tm *aTime = localtime(&theTime); 

int day = aTime->tm_mday; 
int month = aTime->tm_mon + 1; // Month is 0 - 11, add 1 to get a jan-dec 1-12 concept 
int year = aTime->tm_year + 1900; // Year is # years since 1900 
+0

Quizás quiso decir localtime (& time (NULL)); ? – maximus

+0

Corregí la respuesta porque no compilaría como está. No se puede validar con un puntero (es decir, solo un número) por lo que debe colocarlo en una variable primero – Petesh

2

La biblioteca ctime proporciona dicha funcionalidad.

También verifique this. Es otra publicación que podría ayudarte según tu plataforma.

+1

'#include #include using namespace std; int main() { time_t t = time (0); // obtener Ahora struct tm * localtime ahora = (& t); cout << (now-> tm_year + 1900) << '-' << (now-> tm_mon + 1) << '-' << now-> tm_mday << endl; } 'Gracias – Wizard

10

Aquí es la manera chrono (C++ 0x) - ver en vivo en http://ideone.com/yFm9P

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

using namespace std; 

typedef std::chrono::system_clock Clock; 

int main() 
{ 
    auto now = Clock::now(); 
    std::time_t now_c = Clock::to_time_t(now); 
    struct tm *parts = std::localtime(&now_c); 

    std::cout << 1900 + parts->tm_year << std::endl; 
    std::cout << 1 + parts->tm_mon << std::endl; 
    std::cout <<  parts->tm_mday << std::endl; 

    return 0; 
} 
+1

publicó el ejemplo de trabajo en vivo en http://ideone.com/yFm9P – sehe

+0

@PaoloM ese encabezado es obligatorio para [' std :: time_t'] (http://en.cppreference.com/w/cpp/chrono/c/time_t) – sehe

+0

Lo sentimos, en gcc 4.8 se compila sin ''. Se incluye por '' seguro. –

Cuestiones relacionadas