2011-02-28 40 views
66

Quiero obtener la hora actual de mi sistema. Para eso estoy usando el siguiente código en C:Obtener la hora actual en C

time_t now; 
struct tm *mytime = localtime(&now); 
if (strftime(buffer, sizeof buffer, "%X", mytime)) 
{ 
    printf("time1 = \"%s\"\n", buffer); 
} 

El problema es que este código está dando un tiempo aleatorio. Además, el tiempo aleatorio es diferente cada vez. Quiero la hora actual de mi sistema.

+0

duplicado posible de [cómo obtener valor de fecha y hora en el programa C] (https://stackoverflow.com/questions/1442116/how-to-get-date-and-time- value-in-c-program) –

Respuesta

92

Copiar-pegar de here:

/* localtime example */ 
#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; 
} 

(sólo tiene que añadir "vacío" a la principal() Lista argumentos para que esto funcione en C)

+0

¿Alguna idea de cómo hacerlo al revés? cadena a tm *? – Goaler444

+5

Sé que es probablemente un poco tarde y ya han de haber dado cuenta a estas alturas, pero se usaría la función [ 'strptime'] (http://pubs.opengroup.org/onlinepubs/7908799/xsh/strptime.html) en [time.h] (http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html) para convertir de 'char *' a 'struct tm' – KingRadical

+0

Tenga en cuenta que asctime() dejará un \ n al final de la cadena. – h7r

55

inicializar variables now.

time_t now = time(0); // Get the system time 

La función localtime se utiliza para convertir el valor de tiempo en el pasado a una time_tstruct tm, en realidad no recuperar la hora del sistema.

29

Manera fácil:

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

int main(void) 
{ 
    time_t mytime = time(NULL); 
    char * time_str = ctime(&mytime); 
    time_str[strlen(time_str)-1] = '\0'; 
    printf("Current Time : %s\n", time_str); 

    return 0; 
} 
+1

Esto agrega una nueva línea adicional al final. –

+0

@JamesKo Verdadero ... – pm89

-3

chicos tengo una nueva forma de obtener tiempo del sistema. aunque es largo y está lleno de trabajos tontos, pero de esta manera puede obtener el tiempo del sistema en formato entero.

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    FILE *fp; 
    char hc1,hc2,mc1,mc2; 
    int hi1,hi2,mi1,mi2,hour,minute; 
    system("echo %time% >time.txt"); 
    fp=fopen("time.txt","r"); 
    if(fp==NULL) 
     exit(1) ; 
    hc1=fgetc(fp); 
    hc2=fgetc(fp); 
    fgetc(fp); 
    mc1=fgetc(fp); 
    mc2=fgetc(fp); 
    fclose(fp); 
    remove("time.txt"); 
    hi1=hc1; 
    hi2=hc2; 
    mi1=mc1; 
    mi2=mc2; 
    hi1-=48; 
    hi2-=48; 
    mi1-=48; 
    mi2-=48; 
    hour=hi1*10+hi2; 
    minute=mi1*10+mi2; 
    printf("Current time is %d:%d\n",hour,minute); 
    return 0; 
} 
+3

Las bibliotecas de tiempo y las llamadas al sistema en Linux no son asombrosas, pero aun así querrá usarlas, no ir a un comando de shell e intentar analizarlo. Vea las páginas man para time y ctime y rtc. – Dana

+7

Esto es terrible. –

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

void main() 
{ 
    time_t t; 
    time(&t); 
    clrscr(); 

    printf("Today's date and time : %s",ctime(&t)); 
    getch(); 
} 
+0

¿Podría elaborar un poco sobre su solución usando texto puro? – Magnilex

+2

'void main()' debe ser 'int main (void)'. –

6

Para extender la respuesta de @mingos anterior, escribí la siguiente función para formatear mi tiempo a un formato específico ([dd hh mm aaaa: mm: ss]).

// Store the formatted string of time in the output 
void format_time(char *output){ 
    time_t rawtime; 
    struct tm * timeinfo; 

    time (&rawtime); 
    timeinfo = localtime (&rawtime); 

    sprintf(output, "[%d %d %d %d:%d:%d]",timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); 
} 

Más información sobre struct tm se puede encontrar here.

+0

¡Esto ayudó!Gracias. – hiquetj

4

chicos con los que pueden utilizar esta función para obtener la hora local actual. si quieres gmtime, utiliza la función gmtime en lugar de localtime. aplausos

time_t my_time; 
struct tm * timeinfo; 
time (&my_time); 
timeinfo = localtime (&my_time); 
CCLog("year->%d",timeinfo->tm_year+1900); 
CCLog("month->%d",timeinfo->tm_mon+1); 
CCLog("date->%d",timeinfo->tm_mday); 
CCLog("hour->%d",timeinfo->tm_hour); 
CCLog("minutes->%d",timeinfo->tm_min); 
CCLog("seconds->%d",timeinfo->tm_sec); 
6
#include<stdio.h> 
#include<time.h> 

void main() 
{ 
    time_t t; 
    time(&t); 
    printf("\n current time is : %s",ctime(&t)); 
} 
Cuestiones relacionadas