C Standard Library -<time.h>

Introduction

time.hThe header file defines four variable types, two macros, and various functions for manipulating dates and times.

<time.h>It is a header file in the C standard library that provides functions and types for processing and manipulating dates and times. The functions in this header file are used to get the current time, set the time, format time, calculate time differences, and so on.

Constants and Macros

Constants/MacrosDescription
CLOCKS_PER_SECNumber of clock cycles per second.
NULLNull pointer constant.
TIME_UTCRepresents UTC time (C11).

Library variables

Below are the variable types defined in the header file time.h:

Serial NumberVariable & Description
1size_t
Is an unsigned integer type, which issizeofKeyword result.
2clock_t
This is a type suitable for storing processor time.
3time_t is
This is a type suitable for storing calendar time.
4struct tm
This is a structure used to store time and date.

The tm structure is defined as follows:

struct tm {
   int tm_sec;         /* 秒,范围从 0 到 59        */
   int tm_min;         /* 分,范围从 0 到 59        */
   int tm_hour;        /* 小时,范围从 0 到 23        */
   int tm_mday;        /* 一月中的第几天,范围从 1 到 31    */
   int tm_mon;         /* 月,范围从 0 到 11        */
   int tm_year;        /* 自 1900 年起的年数        */
   int tm_wday;        /* 一周中的第几天,范围从 0 到 6    */
   int tm_yday;        /* 一年中的第几天,范围从 0 到 365    */
   int tm_isdst;       /* 夏令时                */
};

Library macros

Below are the macros defined in the header file time.h:

Serial NumberMacro & Description
1NULL
This macro is the value of a null pointer constant.
2CLOCKS_PER_SEC
This macro represents the number of processor clocks per second.

Library functions

Below are the functions defined in the header file time.h:

Serial NumberFunction & Description
1char *asctime(const struct tm *timeptr)
Returns a pointer to a string that represents the date and time of the structure timeptr.
2clock_t clock(void)
Returns the amount of processor time used since program execution began (generally the start of the program).
3char *ctime(const time_t *timer)
Returns a string representing the local time, based on the parameter timer.
4double difftime(time_t time1, time_t time2)
Returns the number of seconds difference between time1 and time2 (time1-time2).
5struct tm *gmtime(const time_t *timer)
The value of timer is decomposed into a tm structure and expressed in Coordinated Universal Time (UTC), also known as Greenwich Mean Time (GMT).
6struct tm *localtime(const time_t *timer)
The value of timer is decomposed into a tm structure and expressed in the local time zone.
7time_t mktime(struct tm *timeptr)
Converts the structure pointed to by timeptr to a time_t value based on the local time zone.
8size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)
Formats the time represented by the structure timeptr according to the formatting rules defined in format, and stores it in str.
9time_t time(time_t *timer)
Calculates the current calendar time and encodes it into time_t format.
10int timespec_get(struct timespec *ts, int base);
Gets the current time (C11).

Example

The following is using<time.h>Examples of some functions in

Get current time:

Example

#include <stdio.h>
#include <time.h>

int main() {
    time_t current_time;
    time(&current_time);
    printf("Current time: %s", ctime(&current_time));

    return 0;
}

Format time:

Example

#include <stdio.h>
#include <time.h>

int main() {
    time_t current_time;
    struct tm *time_info;
    char buffer[80];

    time(&current_time);
    time_info = localtime(&current_time);

    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", time_info);
    printf("Formatted time: %s\n", buffer);

    return 0;
}

Calculate time difference:

Example

#include <stdio.h>
#include <time.h>

int main() {
    time_t start_time, end_time;
    double time_diff;

    time(&start_time);
    // Simulate a time-consuming operation
    for (int i = 0; i < 100000000; i++);

    time(&end_time);
    time_diff = difftime(end_time, start_time);
    printf("Time difference: %.2f seconds\n", time_diff);

    return 0;
}

Usagestruct tm:

Example

#include <stdio.h>
#include <time.h>

int main() {
    struct tm time_info;
    char buffer[80];

    time_info.tm_year = 2024 - 1900;  // Year is calculated from 1900
    time_info.tm_mon = 5;             // June, range from 0 to 11
    time_info.tm_mday = 12;
    time_info.tm_hour = 12;
    time_info.tm_min = 0;
    time_info.tm_sec = 0;
    time_info.tm_isdst = -1;          // Automatically determine whether it is daylight saving time

    mktime(&time_info);

    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &time_info);
    printf("Custom time: %s\n", buffer);

    return 0;
}

Notes

  • UsagelocaltimeandgmtimeWhen, the pointer returned points tostruct tmThe structure is statically stored, and each call overwrites the previous content.
  • UsagemktimeWhen using the function, must ensurestruct tmThe various fields in are valid.
  • UsagestrftimeWhen performing time formatting, ensure that the destination buffer is large enough to avoid buffer overflow.

By understanding and using<time.h>The functions provided make it convenient to manipulate dates and times, enabling the writing of more feature-rich and efficient C programs.

other extensions