130

I want to get the current time of my system. For that I'm using the following code in C:

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

The problem is that this code is giving some random time. Also, the random time is different everytime. I want the current time of my system.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Antrromet
  • 15,294
  • 10
  • 60
  • 75

11 Answers11

159

Copy-pasted from 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;
}

Just add void to the main() arguments list in order for this to work in C

PS: Linux gettimeofday() from <sys/time.h> has tv_sec and tv_microsec

user16217248
  • 3,119
  • 19
  • 19
  • 37
mingos
  • 23,778
  • 12
  • 70
  • 107
  • any idea how to do the other way round? string to tm* ? – Goaler444 Mar 23 '13 at 13:46
  • 11
    I know it's probably a bit late and you have likely figured it out by now, but you would use the [`strptime`](http://pubs.opengroup.org/onlinepubs/7908799/xsh/strptime.html) function in [time.h](http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html) to convert from `char *` to `struct tm` – KingRadical Nov 05 '13 at 19:59
  • 1
    Note that asctime() will leave a \n at the end of the string. – h7r Mar 23 '14 at 22:15
  • 4
    The above code is redundant. asctime(localtime(&rawtime)) is equivalent to a single ctime(&rawtime) function call. – duleshi May 21 '14 at 08:45
  • 2
    FYI - You don't *need* a `time_t` object as the argument for `time()`. Putting `NULL`, `0`, etc as the parameter works to return the current time. – Super Cat Dec 21 '15 at 00:30
  • This is not quite the answer to the question. He is not asking for the date. – kame Sep 13 '19 at 11:48
86

Initialize your now variable.

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

The localtime function is used to convert the time value in the passed time_t to a struct tm, it doesn't actually retrieve the system time.

Erik
  • 88,732
  • 13
  • 198
  • 189
42

Easy way:

#include <time.h>
#include <stdio.h>
#include <string.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;
}
Community
  • 1
  • 1
zishan
  • 584
  • 1
  • 6
  • 12
21

To extend the answer from @mingos above, I wrote the below function to format my time to a specific format ([dd mm yyyy hh: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);
}

More information about struct tm can be found here.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
hexinpeter
  • 1,470
  • 1
  • 16
  • 14
14
#include<stdio.h>
#include<time.h>

void main()
{
    time_t t;
    time(&t);
    printf("\n current time is : %s",ctime(&t));
}
guneet
  • 141
  • 1
  • 2
10

You can use this function to get current local time. if you want gmt then use the gmtime function instead of localtime. cheers

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);
Neuron
  • 5,141
  • 5
  • 38
  • 59
Muhammad Shauket
  • 2,643
  • 19
  • 40
3

If you just need the time without the date.

  time_t rawtime;
  struct tm * timeinfo;
  time( &rawtime );
  timeinfo = localtime( &rawtime );
  printf("%02d:%02d:%02d", timeinfo->tm_hour, timeinfo->tm_min, 
    timeinfo->tm_sec);
kame
  • 20,848
  • 33
  • 104
  • 159
2
#include <stdio.h>
#include <time.h>

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

    printf("Today's date and time : %s",ctime(&t));
    getch();
}
Magnilex
  • 11,584
  • 9
  • 62
  • 84
user309026
  • 31
  • 1
1

LONG VERSION

src: https://en.wikipedia.org/wiki/C_date_and_time_functions

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

int main(void)
{
    time_t current_time;
    char* c_time_string;

    /* Obtain current time. */
    current_time = time(NULL);

    if (current_time == ((time_t)-1))
    {
        (void) fprintf(stderr, "Failure to obtain the current time.\n");
        exit(EXIT_FAILURE);
    }

    /* Convert to local time format. */
    c_time_string = ctime(&current_time);

    if (c_time_string == NULL)
    {
        (void) fprintf(stderr, "Failure to convert the current time.\n");
        exit(EXIT_FAILURE);
    }

    /* Print to stdout. ctime() has already added a terminating newline character. */
    (void) printf("Current time is %s", c_time_string);
    exit(EXIT_SUCCESS);
}

The output is:

Current time is Thu Sep 15 21:18:23 2016

SHORT VERSION:

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

int main(int argc, char *argv[]) {
    time_t current_time;
    time(&current_time);
    printf("%s", ctime(&current_time));

The output is:

Current time is Thu Jan 28 15:22:31 2021
victorkolis
  • 780
  • 13
  • 13
  • 1
    If you want to store the value received in a variable change the short version line 7 for: char *date = ctime(&current_time); – victorkolis Jan 28 '21 at 18:29
1

It is recommonded to use localtime_s instead of localtime. This should work.

time_t current_raw_time = time(0); // System time: number of seconds since 00:00, Jan 1 1970 UTC
struct tm day_time;
localtime_s(&day_time, &current_raw_time);

day_time will have the following members:

struct tm
{
    int tm_sec;   // seconds after the minute - [0, 60] including leap second
    int tm_min;   // minutes after the hour - [0, 59]
    int tm_hour;  // hours since midnight - [0, 23]
    int tm_mday;  // day of the month - [1, 31]
    int tm_mon;   // months since January - [0, 11]
    int tm_year;  // years since 1900
    int tm_wday;  // days since Sunday - [0, 6]
    int tm_yday;  // days since January 1 - [0, 365]
    int tm_isdst; // daylight savings time flag
};

Note that, localtime does not provide milliseconds.

Mahdi
  • 117
  • 1
  • 7
-10

guys i got a new way get system time. though its lengthy and is full of silly works but in this way you can get system time in integer format.

#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;
}
p2013
  • 438
  • 3
  • 6
  • 12
  • 7
    The time libraries and system calls in Linux are not astounding, but even so you would want to use them, not go out to a shell command and try to parse it. See the man pages for time and ctime and rtc. – Dana Jun 26 '14 at 20:28