How to get the date and time values in a C program?

strftime (C89)

Martin mentioned it, here's an example:

main.c

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

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    char s[64];
    size_t ret = strftime(s, sizeof(s), "%c", tm);
    assert(ret);
    printf("%s\n", s);
    return 0;
}

GitHub upstream.

Compile and run:

gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out

Sample output:

Thu Apr 14 22:39:03 2016

The %c specifier produces the same format as ctime.

One advantage of this function is that it returns the number of bytes written, allowing for better error control in case the generated string is too long:

RETURN VALUE

Provided that the result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s. If the length of the result string (including the terminating null byte) would exceed max bytes, then strftime() returns 0, and the contents of the array are undefined.

Note that the return value 0 does not necessarily indicate an error. For example, in many locales %p yields an empty string. An empty format string will likewise yield an empty string.

asctime and ctime (C89, deprecated in POSIX 7)

asctime is a convenient way to format a struct tm:

main.c

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

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    printf("%s", asctime(tm));
    return 0;
}

Sample output:

Wed Jun 10 16:10:32 2015

And there is also ctime() which the standard says is a shortcut for:

asctime(localtime())

As mentioned by Jonathan Leffler, the format has the shortcoming of not having timezone information.

POSIX 7 marked those functions as "obsolescent" so they could be removed in future versions:

The standard developers decided to mark the asctime() and asctime_r() functions obsolescent even though asctime() is in the ISO C standard due to the possibility of buffer overflow. The ISO C standard also provides the strftime() function which can be used to avoid these problems.

C++ version of this question: How to get current time and date in C++?

Tested in Ubuntu 16.04.


To expand on the answer by Ori Osherov

You can use the WinAPI to get the date and time, this method is specific to Windows, but if you are targeting Windows only, or are already using the WinAPI then this is definitly a possibility1:

You can get both the time and date by using the SYSTEMTIME struct. You also need to call one of two functions (either GetLocalTime() or GetSystemTime()) to fill out the struct.

GetLocalTime() will give you the time and date specific to your time zone.

GetSystemTime() will give you the time and date in UTC.

The SYSTEMTIME struct has the following members:

wYear, wMonth, wDayOfWeek, wDay, wHour, wMinute, wSecond and wMilliseconds

You then need to just access the struct in the regular way


Actual example code:

#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()
#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)

int main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)

    SYSTEMTIME t; // Declare SYSTEMTIME struct

    GetLocalTime(&t); // Fill out the struct so that it can be used

    // Use GetSystemTime(&t) to get UTC time 

    printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order

    return 0;
}

(Coded for simplicity and clarity, see the original answer for a better formatted method)

The output will be something like this:

Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572

Useful References:

All the WinAPI documentation (most already listed above):

  • GetLocalTime()
  • GetSystemTime()
  • SYSTEMTIME
  • Time Functions

An extremely good beginners tutorial on this subject by ZetCode:

  • https://zetcode.com/gui/winapi/datetime/

Simple operations with datetime on Codeproject:

  • https://www.codeproject.com/Articles/5546/WinAPI-Simple-Operations-with-datetime

1: As mentioned in the comments in Ori Osherov's answer ("Given that OP started with date +%F, they're almost certainly not using Windows. – melpomene Sep 9 at 22:17") the OP is not using Windows, however since this question has no platform specific tag (nor does it mention anywhere that the answer should be for that particular system), and is one of the top results when Googling "get time in c" both answers belong here, some users searching for an answer to this question may be on Windows and therefore will be useful to them.


time_t rawtime;   
time ( &rawtime );
struct tm *timeinfo = localtime ( &rawtime );

You can also use strftime to format the time into a string.


Use time() and localtime() to get the time:

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

int main()
{
  time_t t = time(NULL);
  struct tm tm = *localtime(&t);
  printf("now: %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}

Tags:

Datetime

C