banner



How To Add Time In C

In today's C programming linguistic communication tutorial nosotros take a look at how to use time and appointment from C programs.
To brand utilise of time and appointment 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 fourth dimension and date. It also contains functions to manipulate and format the fourth dimension and date output. The time.h reference folio contains more information about the different time and engagement functions.

UNIX Time or POSIX Fourth dimension

The function time() returns the blazon time_t. The fourth dimension that is returned represents the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC. It's too called UNIX EPOCH time.

Information technology is widely used not only on Unix-similar operating systems but also in many other computing systems.

Fun note: On Feb thirteen, 2009 at exactly 23:31:30 (UTC), UNIX time was equal to '1234567890'.

Let'southward take a expect at a source code example:

                          #include <stdio.h> #include <time.h> int master () {     time_t sec;     sec = fourth dimension (Cipher);      printf ("Number of hours since January 1, 1970 is %ld \n", sec/3600);     return 0; }          
                          Output instance:      Number of hours since Jan 1, 1970 is 343330          

MS Windows and Time

Microsoft Windows is besides different time for different things. Normally we just place programs that volition compile on UNIX, Linux and Windows, but this fourth dimension we make an exception and show y'all also a Windows case.

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

Windows has it's own SYSTEMTIME structure which stores information on the date and time. For instance: Year, Month, Mean solar day, 60 minutes, Minutes, etc. The format of this structure looks equally follows:

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

Take a wait at the following instance that uses GetSystemTime function to go the UTC time:

                          #include <Windows.h> #include <stdio.h>            void main() { 	SYSTEMTIME str_t; 	GetSystemTime(&str_t);  	printf("Twelvemonth:%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 plan will not work on other platforms. Another thing we need to warn you lot about is that the programme doesn't respond to daylight saving time issues.

                          Output of the Windows case: 		Yr: 2009 		Month: 3 		Day: 3 		Hour: fourteen 		Minute: 59 		Seconds: 23          

Readable Current Local Fourth dimension using ctime

The Unix EPOCH time is not readable for humans. To get a human-readable version of the current local fourth dimension you lot can apply the ctime() role. The office returns a C string containing the date and time information.

This cord is followed past a new-line character ('\due north') and information technology will convert the time_t object pointed by the timer to a C cord containing a human-readable version of the corresponding local time and date.

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

An example of ctime() utilise:

                          #include <time.h> 	#include <stdio.h>            int main(void) 	{ 		time_t mytime; 		mytime = fourth dimension(NULL); 		printf(ctime(&mytime));  		return 0; 	}

The string that is returned will take the following format:

                          Www Mmm dd hh:mm:ss yyyy            World wide web = which day of the calendar week. 	Mmm = calendar month in letters. 	dd = the day of the month. 	hh:mm:ss = the fourth dimension 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 case (notation that the example will not modify your system, it simply prints a new time.):

                          #include <time.h> 	#include <stdio.h>            int principal(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 = five; 		str_time.tm_hour = 10; 		str_time.tm_min = three; 		str_time.tm_sec = 5; 		str_time.tm_isdst = 0;  		time_of_day = mktime(&str_time); 		printf(ctime(&time_of_day));  		render 0; 	}

Annotation: that you can set anything you want for the hour, min and sec equally long as they don't cause a new 24-hour interval to occur.

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

As yous can see we can likewise manipulate the time into the futurity. If you lot look at str_time.tm_hour and the output y'all will come across that they don't represent (10 and 11). This is because of the daylight saving time assault our computer. If y'all likewise have this then you should attempt the following: prepare the str_time.tm_mon to 0 to meet the effect of daylight saving time. The outcome will be that the output at present will be 10.

Using the function difftime

The part 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 instance we measure the time of a loop (that is doing nothing at all.)
Take a await at the case:

                          #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 nada, just loop */  		end = time(NULL); 		printf("The loop used %f seconds.\n", difftime(end, offset)); 		render 0; 	}
                          Output of the example: 		The loop used 2.000000 seconds.          

Timezones

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

                          #include <stdio.h> 	#include <time.h>            #define PST (-8)         #define CET (i)  	int main ()        {                 time_t raw_time;                 struct tm *ptr_ts;                  time ( &raw_time );                 ptr_ts = gmtime ( &raw_time );                  printf ("Time Los Angeles: %2d:%02d\due north",                      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 instance: 		Time Los Angeles: 06:01 		Time Amsterdam: fifteen:01          

Number of clock ticks

It is also possible to use clock ticks elapsed since the commencement of the plan in your own programs past using the function clock(). For instance you can build a wait function or utilize it in your frame per 2d (FPS) office.

Accept a expect at the following await example:

                          #include <stdio.h> 	#include <time.h>            void look ( int sec ) 	{ 		clock_t end_wait; 		end_wait = clock () + sec * CLK_TCK ;  		while (clock() < end_wait) {} 	}  	int main () 	{ 		printf ("Start the Await!\northward");  		wait (5);	/* Look for 5 seconds */  		printf ("Terminate Expect!\north"); 		render 0; 	}

In Determination

Every bit you can run across there are many means to utilise time and dates in your programs. You lot never know when it time to employ fourth dimension functions in your programs, so learn them or at least play with them by making some case programs of your own. Also take a look at our C language agenda tutorial for a more advance employ of the things explained in this tutorial.

This entry was posted in C Tutorials. You can follow any responses to this entry through the RSS ii.0 feed. Both comments and pings are currently airtight. Tweet This! Tweet This! or use to share this mail with others.

How To Add Time In C,

Source: https://www.codingunit.com/c-tutorial-how-to-use-time-and-date-in-c

Posted by: malonelencente.blogspot.com

0 Response to "How To Add Time In C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel