C language to read the basic method of time and date

  • 2020-04-02 03:16:15
  • OfStack

C language time() function: get the current time(in seconds)
The header file:


#include <time.h>

Definition function:


time_t time(time_t *t);

Function description: this function returns the number of seconds that have passed since January 1, 1970 in UTC, from 0:0:0 to the present. If t is not a null pointer, this function also stores the return value in the memory indicated by the t pointer.

Return value: the number of seconds is returned on success, the value ((time_t)-1) is returned on failure, and the reason for the error is in errno.

sample


#include <time.h>
main(){
  int seconds = time((time_t*)NULL);
  printf("%dn", seconds);
}

Execution results:


9.73E+08

C gmtime() function: gets the current time and date
The header file:


#include <time.h>

Definition function:


struct tm *gmtime(const time_t *timep);

Gmtime () converts the information in the time_t structure referred to by the parameter timep to the time and date representation method used in the real world, and then returns the result by the structure tm.

The structure tm is defined as


struct tm{
  int tm_sec; //Represents the current number of seconds. The normal range is 0-59, but allows up to 61 seconds
  int tm_min; //Represents the current score, ranging from 0 to 59
  int tm_hour; //The number of hours from midnight ranged from 0 to 23
  int tm_mday; //The number of days of the current month, ranging from 01 to 31
  int tm_mon; //Represents the current month, from January, ranging from 0 to 11
  int tm_year; //The number of years since 1900
  int tm_wday; //The number of days in a week, starting from Monday, ranges from 0 to 6
  int tm_yday; //The number of days since January 1 this year ranges from 0 to 365
  int tm_isdst; //Daylight saving time flag
};

The time and date returned by this function is not time zone converted, but UTC time.

Return value: the return structure tm represents the current UTC time.

sample


#include <time.h>
main(){
  char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  time_t timep;
  struct tm *p;
  time(&timep);
  p = gmtime(&timep);
  printf("%d%d%d", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday);
  printf("%s%d;%d;%dn", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);
}

Execution results:


2000/10/28 Sat 8:15:38


Related articles: