How to use Time and Date in C
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.
Thanks for sharing but I have problem to enter different date and time value from the computer date and time. I could not find where time(); function is defined.
I don’t know exactly what your question is but the function time() can be used if you include time.h on Unix systems and the function will return the type time_t. Hope it answers your question.
current date:
following date:???????
Don’t exactly know what your question is, but I think your question is: you have a current date. What is the date of the next day?
If this is your question, then the simple answer is +1.
The hard answer is: you have to take the number of days of the month your into account. You also have to make sure it’s not a leap year (see note.) So your calculation get harder.
Note: a leap year does not strictly fall on every fourth year. If a year is divisible by 4, then it is a leap year, but if that year is divisible by 100, then it is not a leap year. However, if the year is also divisible by 400, then it is a leap year.
The leap year calculation can be done like so:
int leap_year (int year)
{
if(year% 4==0 && year%100 != 0 || year%400==0)
return TRUE;
else return FALSE;
}
The best thing you can do is to create a calendar function for yourself. If I have some time tomorrow I will post a example.
As promised in the previous comment, we have created a calendar tutorial that you can find here.
I was reading your blog and thought i would say hi.
Hello,
I was going through your site and found it quite interesting.
I have a question…..
I would like to measure 24 hrs on my machine without waiting for 24 hrs…… is it possible ? (By making some useless calculation in loop).
Could you provide me with an example.
@Sanket
It all depends what you are trying to do. For example do you need precision or is an approximation alright.
For more precision you can find tools like libfaketime online. (On the site you also find the source code of the faketime library.)
For an approximation result, you can use something like the example below:
(note: just a quick and dirty example, no error checking, etc)
#include <stdio.h>
#include <time.h>
void wait ( int sec ) {
int a =0;
clock_t end_wait;
end_wait = clock () + sec * CLK_TCK;
while (clock() < end_wait) {
// Your useless calculations.
a++;
}
printf (“%i\n”, a);
}
void waitspeedup ( int sec, int speedupfactor ) {
int num,a = 0;
num = sec / speedupfactor;
printf (“The new wait time is: %i\n”, num);
clock_t end_wait;
end_wait = clock () + num * CLK_TCK;
while (clock() < end_wait) {
// Your useless calculations
a++;
}
// The fake result (because of speedup factor)
printf (“%i\n”, a);
// Multiply result with speedupfactor to get an approximation
// of the actual results.
printf (“%i\n”, a*speedupfactor);
}
int main () {
printf (“Waiting.1….\n”);
// Wait approx. 12 seconds
wait(12);
printf (“Waiting.2….\n”);
// Wait approx. 12 / 2 = 6 seconds
waitspeedup(12,2);
// There are 86400 seconds in a day
// do something like this 86400/1200=72 sec.
return 0;
}
Hope that this is useful for you. Good luck!
hi..
i want code for this prob..
the librarian wants to calculate due date per book given in issue date, the no. of days in which book is dued can be decided by librarian… for eg if current date is 20/1/11 and no. of due days in which book is returned is 5 days, then it should display due date is 25/1/11..
hw can i get current system date in c.. what header file i should use it to get date….
I want to create and display a countdown timer that displays 60 seconds or less. I need to be able to set
the number of seconds, for the initial display, and have a start and stop button to start or stop the timer.
I want the timer to display a digital countdown of the seconds in real time. In other words the time display
would start at 60 seconds or less and replace each number with the descending next whole number all
the way to zero or double zero.
I also want to be able to adjust the size of the display shown on the screen.
Thanks,
Gary W
admin, do you know how to convert seconds to decade or vice-versa? please help..
@nikko manlangit See the following post – Seconds into decade and visa-versa. I hope you can use the example to solve your own problem. Good Luck!
how to see a specific time
plz help me its an inteview question
how to display a first day of a year when a year is given as input?
Mca mini project
If i want to wait for milli seconds say 10 ms how can i pass the parameter in wait(?).
How to wait for milli seconds?
Don’t use the methods used on this page for high resolution timing en never use wait() function (because it blocks), but instead take a look at the functions sleep() and usleep(). For delays of multiple seconds, your best bet is probably to use sleep(). For delays of at least tens of milliseconds (about 10 ms seems to be the minimum delay), usleep() should work. These functions give the CPU to other processes (“sleep”), so CPU time isn’t wasted. See the manual pages sleep(3) and usleep(3) for details. But be careful with such small time delays, because they can’t behave different on different operating systems.
Take a look at this page that has more about high resolution timing on Linux.
Hope it helps!
Hi, thanks for this useful article.
Tried the following snippet – after mktime() returns, it increments .tm_hour & .tm_isdst – is there any reason for this, doesn’t alter the others? Could be a bit of a minefield programming the difference before and after a mktime() call…
=====
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;
printf(“Start time year = %u\n”, str_time.tm_year);
printf(“Start time mon = %u\n”, str_time.tm_mon);
printf(“Start time mday = %u\n”, str_time.tm_mday);
printf(“Start time hour = %u\n”, str_time.tm_hour);
printf(“Start time min = %u\n”, str_time.tm_min);
printf(“Start time sec = %u\n”, str_time.tm_sec);
printf(“Start time isdst = %u\n”, str_time.tm_isdst);
time_of_day = mktime(&str_time);
printf(“Start time year = %u\n”, str_time.tm_year);
printf(“Start time mon = %u\n”, str_time.tm_mon);
printf(“Start time mday = %u\n”, str_time.tm_mday);
printf(“Start time hour = %u\n”, str_time.tm_hour);
printf(“Start time min = %u\n”, str_time.tm_min);
printf(“Start time sec = %u\n”, str_time.tm_sec);
printf(“Start time isdst = %u\n”, str_time.tm_isdst);
printf(“Start time hour = %u\n”, str_time.tm_hour);
printf(“%s”, ctime(&time_of_day));
Ok, figured it – if you set tm_isdst to a value that isn’t you’re actual daylight saving, it corrects it and adjusts the hour appropriately!
hi sir,
Can i have the program for real time clock…
The clock must run continuously like a wall clock…
plz send me..
thank you.
is it possible to calculate execution time in milliseconds or nanoseconds?how?
hello,i want to compare system date with another date(whole date like dd-mm-yyyy not only date)
Have you any solution for this?
Thanks in advance
I’m currently using a combination of boland C++, ARCOM pc104 card running DOS 6.22.
Within my program i have the following:-
putenv(“TZ=PST8PD7”);
tzset();
i have also tried
putenv(“TZ=PST8PD7,M4.1.0/2,M11.1.0/2”);
tzset();
In each case i use the localtime() function to extract the time data and display, this process seems to work fine for the zone time differrence e.g 8 hours, however the daylight saving is completely ignored. tm_isddt does indicate when daylight is in effect although this always happens at same UK start and stop time irrespective of any changes i make.
question: How do i get the time to change according to specified daylight saving start, stop dates and daylight saving time differences.
Many thanks in anticipation.
Andy
it is really interesting.can i count the time in c that is 24hrs and after 24 hrs.A day will be incremented like that….
how do i compile this… enyone send me a complie code
great post admin, really helpful.. i also would like to ask similar question to ram
give the date and time code current update time in output screen
this helped a lot and it is tried and tested. Thank you. 🙂
Hi,,
I am using windows 7 and compiler is BloodShed DevC++.. How can I write a delay function in C using system clock? Any Idea? Please help me..
@arun: maybe you can use the Sleep() function defined in windows.h? Take a look at the following example:
#include <stdio.h>
#include <windows.h>
int main () {
printf(“wait some time\n”);
Sleep(10000);
printf(“Goodbye Cruel World\n”);
}
Hope this helps, good luck!
i am having problem with the getsystemtime() function.. they are saying prototype expected. i copied the exact code
@arunava: I’ve just copied and paste the example with the GetSystemTime() function and it compiles on windows (visual studio) fine. So I don’t know why it is not compiling for you, here are some things you should notice: First of, in your comment you say getsystemtime() function but it is GetSystemTime() (so capital letters). Second, include Windows.h. Third the minimum supported client is Windows 2000 Professional and the minimum supported server is Windows 2000 Server. More information on Windows time function you can find here. I hope it helps!
how do i print the current date in the format dd/month/yyyy
@Shan Roy: to print the current date in a specific format isn’t that difficult, just use strftime function to convert to a specific string format.
Take a look at the following example:
#include <time.h>
#include <stdio.h>
int main() {
time_t nowtime;
struct tm *ptr_time;
char buffer[15];
//Get the current time
time(&nowtime);
//localtime returns a pointer to a tm structure
ptr_time = localtime(&nowtime);
//Convert time to specific string
strftime(buffer, 15, “%d/%m/%Y”, ptr_time);
printf(“%s\n”, buffer);
//or the day and month turned around
strftime(buffer, 15, “%m/%d/%Y”, ptr_time);
printf(“%s\n”, buffer);
return 0;
}
[…] http://www.codingunit.com/c-tutorial…-and-date-in-c ctime() mktime() console: Code: […]
Many thanks for this! I’ve read page after page about time.h and it’s functions, but none explain it in a way that one can actually make it do something useful. And some contain examples that don’t even work!
If i may criticise one point – your timezones example has the potential to go over midnight, and even negative. I achieved it using mktime, again using your examples above, to ensure the hours remained between 0 and 23 (inclusive).
Despite this, i am really very grateful. Thankyou!
I’m having problem on time function. Can you share some idea on showing countdown of the time left .
Thanks in advance
I want to make a program with c++ using date condition
if date is 24-Mar-13 go next stage
if date is under 24-mar-13 condition is back
or program is not go next stage
pls help me
goood work!!
I want to make a program in c in which i want to calculate how much time my program take to execute. how to do this..
thanks in advance.
thnks for your info…
quite interesting….!
i wanna ask that why we use
time_t mytime;
mytime = time(NULL);
printf(ctime(&mytime));
why [time(null);] statement is used
and one more thing how we can make a program of converting current tym into 24 hr system
Hi,
I want to fetch the Current system date (minus time) … in the following format
DD/mm/yyyy and want to store in a variable.
From the current system date, i want to know the Day? Example
If current system date is 05/10/2013 (i.e. 5th Oct 2013) then the value of Day should be returned as Saturday.
I need this to build further logic in C if the Day is either Saturday or Sunday.
Thanks
how can we findout the time of seconds and if this necessary to use the term time_t ????