·  C – Date & Time

 

- Info:

  - This tutorial shows how to work with time and date.

 

- Timer:

  - Create C Console Application Test.c.

  - First call to function clock() starts the timer.

  - Each subsequent call to clock() returnes elapsed miliseconds as long from when the timer was started.

  - This example is based on http://www.cplusplus.com/reference/clibrary/ctime/.

 

    Test.c

    #include <stdio.h>   //printf

    #include <time.h>    //clock

    #include <windows.h> //Sleep

   

    int main(void) {

   

      long milisec1, milisec2;

   

      clock();                  //Start timer.

      Sleep(3000);              //Wait 3 seconds.

      milisec1 = clock();       //Get elapsed time.

      Sleep(2000);              //Wait 5 seconds.

      milisec2 = clock();       //Get elapsed time.

      printf("Elapsed time: %ld %ld. \n", milisec1, milisec2);

   

      return 1;

   

    }

 

- Date/Time:

  - Create C Console Application Test.c.

  - Function time() returns current time in seconds as long.

  - Function localtime() converts those seconds into structure containing Year, Month, Day and so on.

  - This example is based on http://www.cplusplus.com/reference/clibrary/ctime/.

 

    Test.c

    #include <stdio.h>

    #include <time.h>

   

    int main(void) {

   

      //DECLARE VARIABLES.---------------------------------------------------------------

      time_t seconds;       //int value with miliseconds.

      struct tm *dateTime;  //Structure with date components like: Year, Month, ...

      

      //GET DATE.------------------------------------------------------------------------

      time(&seconds); 

      dateTime = localtime(&seconds);

      

      //DISPLAY DATE.--------------------------------------------------------------------

      printf("%02d.%02d.%04d   ", dateTime->tm_mday, dateTime->tm_mon + 1, dateTime->tm_year + 1900);

      printf("%02d.%02d.%02d \n", dateTime->tm_hour, dateTime->tm_min    , dateTime->tm_sec        );

   

      return 1;

   

    }