[LinuxC] Time, time zone, related commands and functions

Article directory

  • 1. Preface
    • 1.1 Time and time zone
      • 1.11 Time
      • 1.12 Time zone
    • 1.2 Commands to view time and time zone
      • 1.21 Windows
      • 1.22 Linux
  • 2. C language functions
    • 2.1 General
      • 2.11 Introduction to functions
      • 2.12 Introduction to data types
    • 2.2 Windows and Linux-specific functions
    • 2.3 C language example

1. Preface

1.1 Time and time zone

1.11 Time

Time is a quantity used to describe changes in the motion of an object. It can be defined by the ratio of the movement distance of light to the constant c. Different objects or observers may experience time passing at different speeds. This is the time dilation effect in the theory of relativity…

There are many special concepts in time, some of which are related to calendars, dates, and time measurements. Here are some common special time concepts:

  1. Leap Year: In order to match the earth’s rotation period, there is a leap year every four years. A leap year has 366 days instead of 365 days in an ordinary year. February will have one more day, making it 29 days.

  2. Leap Second (Leap Second): In order to maintain synchronization between Coordinated Universal Time (UTC) and International Atomic Time (TAI), leap seconds are inserted from time to time. This means there is an extra second on a given day, usually inserted at the last minute of UTC.

  3. Daylight Saving Time: Some countries and regions move their clocks forward one hour during the summer, usually starting in spring and ending in autumn. This is designed to save energy and extend your daytime activities.

  4. Greenwich Mean Time (GMT): A time standard based on the Royal Observatory in Greenwich, London, England. UTC is now generally considered the international time standard, but GMT is still used in some contexts.

  5. Epoch: An epoch is a specific date or point in time, often used as the starting point of time in computer systems. For example, the UNIX operating system uses midnight (Greenwich Mean Time) on January 1, 1970 as the epoch.

  6. Week: A week is a periodic unit of the week, usually with seven days. Each day of the week has its own name (e.g. Monday, Tuesday) and abbreviation (e.g. Monday, Tuesday).

  7. Season: The seasons are the four periods of the year, namely spring, summer, autumn and winter. The start and end of the season vary by geographic location.

  8. Sunset and sunrise: Sunset is the time when the sun disappears below the horizon, and sunrise is the time when the sun rises above the horizon. These times vary between seasons and locations.

  9. Timestamp: A timestamp is a representation of a specific point in time, usually in the form of seconds or milliseconds. Timestamps are used in computer systems to record time information about events and operations.

These special concepts of time play an important role in daily life, science, computer programming, and global coordination. They help us accurately measure and record time to meet various needs and requirements.

Time Standard:

Time standard Definition Features
TAI International Atomic Time is a A time scale measured using the combined output of about 400 high-precision atomic clocks provides the exact speed our clocks should run
UTC Coordinated Universal Time is a time scale used to determine local time around the world . It consists of two parts: TAI and UT1 Due to changes in the earth’s rotation speed, there will be a difference between UTC and TAI. In order to keep the difference between UTC and UT1 within 0.9 seconds, leap seconds are added or subtracted from UTC
UT1 Universal time, also known as astronomical time, refers to the rotation of the Earth. It is used to compare the speed provided by TAI with the actual length of a day on Earth Affected by changes in the Earth’s rotation speed, earthquakes, tides and other factors
GMT Greenwich Mean Time, referring to Royal Green, located in the suburbs of London The standard time of Widget Observatory, because the prime meridian is defined as the longitude passing there UTC and GMT can be regarded as indistinguishable. GMT is based on atomic time and is more accurate. , generally used when it does not need to be accurate to seconds, it is regarded as equivalent

1.12 time zone

The Earth is divided into 24 time zones, each representing a specific range of longitude on the Earth. The purpose of time zones is to maintain relatively consistent times in different places on Earth in order to coordinate activities across multiple geographic areas.

This is easy to understand. The earth is a sphere, the sun cannot illuminate it at the same time, and the angle of the sun is different in different places.

The concept of time zones originated with the development of railroads and telegraphs. In the mid-19th century, railroads and telegraphs made it possible to move information and people quickly, but different cities used different local times, which led to confusion. Therefore, the International Time Conference was held in 1884 and decided to divide the earth into 24 time zones, each time zone differing by 15 degrees of longitude.

Most of the world has adopted this time zone system, with some exceptions such as India and New Nepal time zones, which use different offsets. In addition, some countries also adopt the daylight saving time system to adjust their clocks to save energy.

In addition to daily life. When you purchase a server in another foreign time zone and deploy certain services on it, you may encounter a situation where the time zone is not set correctly and cannot run; or a common situation is: the computer time (time zone) is incorrect Browsers and applications may be unable to connect to the Internet.

There are 24 time zones, and the time difference between adjacent time zones is one hour. However, the territory of many countries spans multiple time zones (for example, it is already evening in Shanghai, but the sun has not yet set in Xinjiang). In order to avoid confusion, the country will set a single time standard. For example, China Standard Time (CST) is also called Beijing Time (Beijing Time, BT).

As shown above, Eastern Hemisphere time is usually earlier than Western Hemisphere time. The time dividing line between the Eastern and Western Hemispheres is called the International Date Line (IDL). The International Date Line is a virtual line that runs east-west on the earth, roughly along a line near 180 degrees longitude. One side of this line is considered the Eastern Hemisphere and the other is the Western Hemisphere.

1.2 Commands to view time and time zone

1.21 Windows

Not to mention the graphical interface.

  • tzutil is a command-line tool for viewing and setting time zones on Windows systems:
    • tzutil /g: View the current time zone of the local computer.
    • tzutil /l: View all valid time zone IDs and their names.
    • tzutil /s : Set the local computer’s time zone to the specified ID.
  • date and time are command line tools for viewing and modifying date and time in Windows systems:
    • date: View or modify the current date of the local computer.
    • time: View or modify the current time of the local computer.
    • date /t: Only view the current date of the local computer without modifying it.
    • time /t: Only view the current time of the local computer without modifying it.

1.22 Linux

Check out the help manual yourself for more parameters.

  1. View current time:

    • Use the date command to view the current system time.
    date
    
  2. View current date:

    • Use the date command and specify the format option -d to view the current system date.
    date -d
    
  3. View current time zone:

    • Use the timedatectl command to view the current time zone setting.
    timedatectl
    
  4. See a list of available time zones:

    • Use the timedatectl command to list all time zones supported by the system.
    timedatectl list-timezones
    
  5. Change time zone:

    • Use the timedatectl command to change the system’s time zone setting. For example, to change the time zone to “America/New_York”:
    sudo timedatectl set-timezone America/New_York
    
  6. Enable/disable daylight saving time:

    • Use the timedatectl command to enable or disable daylight saving time. For example:
    sudo timedatectl set-timezone America/New_York
    sudo timedatectl set-local-rtc 1
    
  7. Synchronize system time:

    • Use the ntpdate command to manually synchronize system time with a network time server. For example:
    sudo ntpdate time.nist.gov
    

In Linux systems, the time command is used to measure the time taken to execute a command or program. It helps evaluate program performance as well as execution time. To use the time command, type time in the terminal, followed by the command you want to execute. Here are examples:

time lscpu

The above command will measure the time required to execute the lscpu command and display three key timing information:

  1. real: The actual elapsed time, the total time from the start of the command to the completion.
  2. user: CPU user mode time, that is, the time the command spends in user space.
  3. sys: CPU kernel mode time, that is, the time the command spends in kernel space.

For example, if you execute the time lscpu command, you will see the following output:

...
real 0m0.028s
user 0m0.004s
sys 0m0.024s

This means that the ls command actually took 0.028 seconds, of which 0.004 seconds used the CPU in user mode and 0.024 seconds used the CPU in kernel mode.

The time command is useful for evaluating the performance of a command or program, especially when optimizing code or comparing execution times of different implementations. Please note that the time command is not a command used to set the system time or time zone, but a tool used to measure the command execution time.

2. C language function

2.1 General

2.11 Function Introduction

Located in time.h:

< /table>

2.12 Introduction to data types

time_t definition:

typedef long time_t;

This definition means that time_t is a long data type. In many systems, time_t is defined as the number of seconds since January 1, 1970 and is used to represent a timestamp. The exact type of time_t may vary on different systems and compilation environments, but usually it is defined as an integer type.

The implementation of time_t may vary for different operating systems and compilers, but its purpose is to provide a portable way to represent time. When using time_t, programmers should follow the documentation and specifications of the relevant functions in the standard library to ensure compatibility on different platforms.

January 1, 1970, was chosen as the starting point of UNIX time because it was the date chosen by American computer scientist Ken Thompson, one of the creators of the UNIX operating system, in the UNIX implementation at that time.

This date was actually chosen as a convention because computer scientists needed a standard way to represent time. UNIX time is a way of measuring time in seconds, starting at 0:00:00 on January 1, 1970 (UTC) and representing the number of seconds since that time. This date was chosen as the starting point of UNIX time mainly because it was relatively easy to calculate and was convenient on UNIX systems of the time.

In addition, January 1, 1970, 0:00:00 (UTC) was also chosen as the UNIX time starting point because it is in Coordinated Universal Time (UTC) and avoids daylight savings when calculating time. time (DST) and other time zone changes. This allows UNIX time to be consistent across different regions and different computer systems.

UNIX time, starting on January 1, 1970, is widely used in computer science and software engineering, especially in operating systems, databases, file systems, and network protocols. Therefore, this date becomes an important time base for representing and calculating time intervals, as well as for exchanging timestamps between computer systems.

Structure prototype: (I’ll write down what was mentioned in Section 2.2 here by the way)

Look at the comments a little, for example, the month starts from 0, and the year starts from 1900. (Write -10 in 1890)

  1. struct tm structure (defined in ):

    struct tm {<!-- -->
        int tm_sec; // seconds (0-59)
        int tm_min; // minutes (0-59)
        int tm_hour; // hour (0-23)
        int tm_mday; // Number of days in the month (1-31)
        int tm_mon; // month (0-11, 0 means January)
        int tm_year; // Year (number of years since 1900)
        int tm_wday; // day of the week (0-6, 0 means Sunday)
        int tm_yday; //The number of days in the year (0-365)
        int tm_isdst; // Daylight saving time flag (positive number means DST, 0 means not DST, negative number means uncertain)
    };
    
  2. SYSTEMTIME structure (defined in ):

    typedef struct _SYSTEMTIME {<!-- -->
        WORD wYear; // year
        WORD wMonth; // month
        WORD wDayOfWeek; // Day of the week (0-6, 0 means Sunday)
        WORD wDay; //The number of days in the month (1-31)
        WORD wHour; // hour (0-23)
        WORD wMinute; // minutes (0-59)
        WORD wSecond; // Second (0-59)
        WORD wMilliseconds; // milliseconds
    } SYSTEMTIME;
    
  3. struct timeval structure (defined in , typically used on Linux and Unix systems):

    struct timeval {<!-- -->
        long tv_sec; // seconds
        long tv_usec; // microseconds
    };
    
  4. struct timespec structure (defined in , typically used on Linux and Unix systems):

    struct timespec {<!-- -->
        time_t tv_sec; // seconds
        long tv_nsec; // nanoseconds
    };
    

These structures are used to represent various aspects of time, including year, month, day, hour, minute, second, etc., and are often used for input and output in time-related C functions. Please note that the SYSTEMTIME structure is Windows-specific, while the struct timeval and struct timespec structures are commonly used on Linux and Unix systems.

2.2 windows and Linux specific functions

Under Windows:

Function Function prototype Input Output Function Notes
time() time_t time(time_t *time_ptr) ; time_ptr – a time_t pointer time_t – a time value Returns the number of seconds since January 1, 1970 Calculated in local time
ctime() char *ctime(const time_t *time_ptr); time_ptr – a time_t pointer char * – time string Converts a time value into a readable date and time string The string may end with a newline character and needs to be handled appropriately
strftime() size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr); str – character array, maxsize – maximum number of characters, format – Formatted string, timeptrstruct tm structure size_t – Number of formatted characters Format the time value into a custom string format You need to use the appropriate format string, and the structure tm needs to be set correctly
gmtime() struct tm *gmtime(const time_t *time_ptr); time_ptr – a time_t pointer struct tm * – a time structure Convert time values to world standards Time (UTC) struct tm structure You need to pay attention to the difference between time zones and daylight saving time. The returned structure represents UTC time
localtime() struct tm *localtime(const time_t *time_ptr); time_ptr – A time_t pointer struct tm * – time structure Convert time value to local time< /strong> struct tm Structure Time zone and daylight saving time rules will affect the results, and the returned structure represents the local time
difftime() double difftime(time_t time1, time_t time2); time1 and time2 – two time_t values doubletime difference (seconds) Calculate the time difference between two time values Returns a floating point number that can be used to compare the time difference between different times
mktime() time_t mktime(struct tm *timeptr); timeptrstruct tm structure time_t – time value Converts struct tm structure The time represented is converted into a time value of type time_t The structure field needs to be set correctly, and negative years are not supported
asctime() char *asctime(const struct tm *timeptr); timeptr struct tm structure char * – time string replaces struct tm structure Convert the time represented to a readable date and time string The returned string may end in a newline character and needs to be handled appropriately
Function Function prototype Header file Input Output Function Notes
GetSystemTime() void GetSystemTime(SYSTEMTIME *lpSystemTime); windows.h lpSystemTime – a SYSTEMTIME Structure pointer None Get the system time (UTC + ) and return it in the form of year, month, day, hour, minute, second, etc. None
GetLocalTime() void GetLocalTime(SYSTEMTIME *lpSystemTime); windows .h lpSystemTime – a SYSTEMTIME structure pointer None Get local time, taking into account time zone and daylight saving time rules, returned in the form of year, month, day, hour, minute, second, etc. None
GetTickCount() DWORD GetTickCount(void); windows.h None Returns the number of milliseconds since system startup None

Under Linux:

Function Function prototype Header file Input Output Function Notes
gettimeofday() int gettimeofday(struct timeval *tv, struct timezone *tz); sys/time.h tv – A struct timeval structure pointer, tz – A struct timezone structure pointer (NULL can be passed in) 0 ( Success) or -1 (failure) Get the current time, including seconds and microseconds, which can be used for high-precision timing Need to check the return value to handle errors, struct timezone is ignored on many systems
clock_gettime() int clock_gettime(clockid_t clk_id, struct timespec *tp); time.h clk_id – clock identifier, tp – a struct timespec structure pointer 0 (success) or -1 (failure) Get high-resolution time information, different clock sources can be selected Need to check the return value to handle errors, clock identification and supported clock sources vary by system Varies

2.3 C language example

Let’s take a simple example and combine it with the previous structure definition, function prototype and function introduction. The application is still very wide.

You need to pay attention to some conversions, especially the gm structure. The time_t variable is calculated from 1970-1-1, and the members of the tm structure variable are calculated from 1900. The number of months, days of the week, and days start from 0. start.

struct tm {<!-- -->
    int tm_sec; // seconds (0-59)
    int tm_min; // minutes (0-59)
    int tm_hour; // hour (0-23)
    int tm_mday; // Number of days in the month (1-31)
    int tm_mon; // month (0-11, 0 means January)
    int tm_year; // Year (number of years since 1900)
    int tm_wday; // day of the week (0-6, 0 means Sunday)
    int tm_yday; //The number of days in the year (0-365)
    int tm_isdst; // Daylight saving time flag (positive number means DST, 0 means not DST, negative number means uncertain)
};

Linux:

Output:


Code example:

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>

int main() {<!-- -->
    struct timeval current_time;
    struct tm set_time ={<!-- --> 0, 0, 0, 1, 0, 120, },*diff_readable;
    char time_str[30], *p;

    if (gettimeofday( & amp;current_time, NULL) == 0) {<!-- -->
        p = ctime( &current_time.tv_sec);
        printf("Current time is %s", p); // Note that the string here originally ends with a newline character
        printf("It has passed %ld seconds %ld microseconds since 1970-1-1\\
", current_time.tv_sec, current_time.tv_usec);
    } else {<!-- -->
        perror("gettimeofday");
    }

    time_t set_t = mktime( & amp;set_time);
    printf("I set a time: %s", asctime( & amp;set_time));

    double diff = difftime(current_time.tv_sec, set_t);
    printf("Time diff between current time and set time is %ld seconds\\
",(long)(diff));

    time_t diff_time = (time_t)diff;
    diff_readable = localtime( & amp;diff_time);
    printf("Transform to be readable :%d yesrs %d months %d days %d hours\\
",
           diff_readable->tm_year-70, diff_readable->tm_mon + 1,
           diff_readable->tm_mday, diff_readable->tm_hour);

    return 0;
}

Under Windows:

Using Windows API:
Output:

Current time:2023-10-6-14:47
Current time:2023-10-6-22:47
It has passed 249 hours since PC started

Source code:

#include <stdio.h>
#include <string.h>
#include <windows.h>

int main() {<!-- -->
SYSTEMTIME system_time = {<!-- -->0}, local_time = {<!-- -->0};
GetSystemTime( & amp;system_time);
printf("Current time:%u-%u-%u-%u:%u\\
",system_time.wYear, system_time.wMonth, system_time.wDay,
system_time.wHour, system_time.wMinute);

GetLocalTime( & amp;local_time);
printf("Current time:%u-%u-%u-%u:%u\\
", local_time.wYear, local_time.wMonth, local_time.wDay,
local_time.wHour, local_time.wMinute);

printf("It has passed %lu hours since PC started\\
",GetTickCount()/(1000*60*60));
return 0;
}

Use time.h:
Output:

Current time(local): Fri Oct 6 23:00:39 2023

Current time(UTC): Fri Oct 6 15:00:39 2023

Source code:

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

int main() {<!-- -->
char current_time[30] = {<!-- -->0}, *p;
time_t time_second;
struct tm* utc_time;

time(& amp;time_second);
p = current_time;
p = ctime( & amp;time_second);
printf("Current time(local): %s\\
",p);

utc_time = gmtime( & amp;time_second);
time_t UTC = mktime(utc_time);
p = ctime( & amp;UTC);
printf("Current time(UTC): %s\\
",p);
return 0;
}

Summary:

Generally, you can use the functions of time.h to complete all the work, but it will be faster and more accurate to use the corresponding API to obtain the time under a specific system.