Introduction to the basic method of converting time in C language

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

C mktime() function: converts time to the number of seconds passed
The header file:


#include <time.h>

Definition function:


time_t mktime(strcut tm * timeptr);

Mktime () is used to convert the tm structure data referred to by the parameter timeptr to the number of seconds elapsed in UTC from 0:0:0:00 on January 1, 1970 AD.

Return value: returns the number of seconds elapsed.

Example: time() is used to get the time(seconds), localtime() is used to convert to structtm, and mktine() is used to convert the structtm to the original number of seconds.


#include <time.h>
main(){
  time_t timep;
  strcut tm *p;
  time(&timep);
  printf("time() : %d n", timep);
  p = localtime(&timep);
  timep = mktime(p);
  printf("time()->localtime()->mktime():%dn", timep);
}

Execution results:


time():974943297 time()->localtime()->mktime():974943297


C localtime() function: gets the current time and date and converts to the localtime
The header file:


#include <time.h>

Definition function:


struct tm *localtime(const time_t * timep);

Localtime () 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. Please refer to gmtime() for the definition of structure tm. The time and date returned by this function has been converted to the local time zone.

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

sample


#include <time.h>
main(){
  char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  time_t timep;
  struct tm *p;
  time(&timep);
  p = localtime(&timep); //Get local time
  printf ("%d%d%d ", (1900+p->tm_year), (l+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 11:12:22


Related articles: