How to use Time and Date in C - JohnHau/mis GitHub Wiki

In today’s C programming language tutorial we take a look at how to use time and date from C programs. To make use of time and date function you need to include the time.h header file from the standard C library.

This header file contains functions and macros that provide standardized access to time and date. It also contains functions to manipulate and format the time and date output. The time.h reference page contains more information about the different time and date functions.

UNIX Time or POSIX Time The function time() returns the type time_t. The time that is returned represents the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC. It’s also called UNIX EPOCH time.

It is widely used not only on Unix-like operating systems but also in many other computing systems.

Fun note: On February 13, 2009 at exactly 23:31:30 (UTC), UNIX time was equal to ‘1234567890’.

Let’s take a look at a source code example:

#include <stdio.h> #include <time.h> int main () { time_t sec; sec = time (NULL);

printf ("Number of hours since January 1, 1970 is %ld \n", sec/3600);
return 0;

}

Output example: Number of hours since January 1, 1970 is 343330 MS Windows and Time Microsoft Windows is also different time for different things. Normally we only place programs that will compile on UNIX, Linux and Windows, but this time we make an exception and show you also a Windows example.

(Note: that the other programs in this tutorial should also work and compile on Windows.)

Windows has it’s own SYSTEMTIME structure which stores information on the date and time. For instance: Year, Month, Day, Hour, Minutes, etc. The format of this structure looks as follows:

typedef struct _SYSTEMTIME {
	WORD wYear;
	WORD wMonth;
	WORD wDayOfWeek;
	WORD wDay;
	WORD wHour;
	WORD wMinute;
	WORD wSecond;
	WORD wMilliseconds;
} SYSTEMTIME;

Take a look at the following example that uses GetSystemTime function to get the UTC time:

#include <Windows.h> #include <stdio.h>

void main() { SYSTEMTIME str_t; GetSystemTime(&str_t);

printf("Year:%d\nMonth:%d\nDate:%d\nHour:%d\nMin:%d\nSecond:% d\n"
,str_t.wYear,str_t.wMonth,str_t.wDay
,str_t.wHour,str_t.wMinute,str_t.wSecond);

} Note: the windows.h include, this program will not work on other platforms. Another thing we need to warn you about is that the program doesn’t respond to daylight saving time issues.

Output of the Windows example:
	Year: 2009
	Month: 3
	Day: 3
	Hour: 14
	Minute: 59
	Seconds: 23

Readable Current Local Time using ctime The Unix EPOCH time is not readable for humans. To get a human-readable version of the current local time you can use the ctime() function. The function returns a C string containing the date and time information.

This string is followed by a new-line character (‘\n’) and it will convert the time_t object pointed by the timer to a C string containing a human-readable version of the corresponding local time and date.

Please note: that the functions ctime() and asctime() share the array which holds the time string. If either one of these functions is called, the content of the array is overwritten.

An example of ctime() use:

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

int main(void)
{
	time_t mytime;
	mytime = time(NULL);
	printf(ctime(&mytime));

	return 0;
}

The string that is returned will have the following format:

Www Mmm dd hh:mm:ss yyyy

Www = which day of the week.
Mmm = month in letters.
dd = the day of the month.
hh:mm:ss = the time in hour, minutes, seconds.
yyyy = the year.

Output example:
	Tue Feb 26 09:01:47 2009

Manipulating the time structure with mktime() It is also possible to manipulate the time structure and to create your own time using mktime().

Let’s look at an example (note that the example will not change your system, it only prints a new time.):

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

int main(void)
{
	struct tm str_time;
	time_t time_of_day;

	str_time.tm_year = 2012-1900;
	str_time.tm_mon = 6;
	str_time.tm_mday = 5;
	str_time.tm_hour = 10;
	str_time.tm_min = 3;
	str_time.tm_sec = 5;
	str_time.tm_isdst = 0;

	time_of_day = mktime(&str_time);
	printf(ctime(&time_of_day));

	return 0;
}

Note: that you can set anything you want for the hour, min and sec as long as they don’t cause a new day to occur.

Output of the program:
	Thu Jul 05 11:03:05 2012

As you can see we can also manipulate the time into the future. If you look at str_time.tm_hour and the output you will see that they don’t correspond (10 and 11). This is because of the daylight saving time set on our computer. If you also have this then you should try the following: set the str_time.tm_mon to 0 to see the effect of daylight saving time. The result will be that the output now will be 10.

Using the function difftime The function difftime() is a very useful function, because it can be used to measure the performance time of a certain part of code. For instance in our example we measure the time of a loop (that is doing nothing at all.) Take a look at the example:

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

int main(void)
{
	time_t start,end;
	volatile long unsigned counter;

	start = time(NULL);

	for(counter = 0; counter < 500000000; counter++)
		; /* Do nothing, just loop */

	end = time(NULL);
	printf("The loop used %f seconds.\n", difftime(end, start));
	return 0;
}

Output of the example:
	The loop used 2.000000 seconds.

Timezones It is also possible to work with different timeszones by using gmtime() to convert calendar time to UTC. If you know the UTC time you can add CET, for example Amsterdam +1 hour. Take a look at the following example:

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

    #define PST (-8)
    #define CET (1)

int main ()
   {
            time_t raw_time;
            struct tm *ptr_ts;

            time ( &raw_time );
            ptr_ts = gmtime ( &raw_time );

            printf ("Time Los Angeles: %2d:%02d\n",
                 ptr_ts->tm_hour+PST, ptr_ts->tm_min);
            printf ("Time Amsterdam: %2d:%02d\n",
                 ptr_ts->tm_hour+CET, ptr_ts->tm_min);
	return 0;
     }

Output of the example:
	Time Los Angeles: 06:01
	Time Amsterdam: 15:01

Number of clock ticks It is also possible to use clock ticks elapsed since the start of the program in your own programs by using the function clock(). For instance you can build a wait function or use it in your frame per second (FPS) function.

Take a look at the following wait example:

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

void wait ( int sec )
{
	clock_t end_wait;
	end_wait = clock () + sec * CLK_TCK ;

	while (clock() < end_wait) {}
}

int main ()
{
	printf ("Start the Wait!\n");

	wait (5);	/* Wait for 5 seconds */

	printf ("End Wait!\n");
	return 0;
}

In Conclusion As you can see there are many ways to use time and dates in your programs. You never know when it time to use time functions in your programs, so learn them or at least play with them by making some example programs of your own. Also take a look at our C language calendar tutorial for a more advance use of the things explained in this tutorial.

⚠️ **GitHub.com Fallback** ⚠️