[Script language] Shell Script - date acquisition, setting and delay operations

        This article has a total of 700 words and the estimated reading time is 3 minutes.

Table of contents

basic concepts

basic grammar

        Print current date

        When printing epoch

        Convert date to epoch

        Print date in required format

        Set date and time


basic concepts

        Bash can help us print dates in different formats, set dates, or perform operations based on date or time, etc.

        In Unix-like systems, a date is stored as an integer, the size of which is the number of seconds elapsed since January 1, 1970, 0:00:00 Coordinated Universal Time (UTC). This way of keeping time is called epoch time or Unix time.

basic grammar

        You can use different formats to output and set dates.

        1) Print current date
date

        Output sample 

        2) When printing the epoch
date +%s

        Output sample 

        3) Convert date to epoch time
date --date "Jul 09 2023" +%s

        Output sample  

        If you want to know the day of the week from the date, you can replace the following %s with %A, for example

date --date "Jul 09 2023" +%A

        Output sample  

        For conversion content, please refer to the table below and convert the date as needed.

Format Convert content
%A / %a Week
%I / %H Hour
%M minute
%S Second
%N nanosecond
%y / %Y Year
%b / %B moon
%d Day
%D Fixed format date (mm/dd/yy)
Epoch %s
        4) Print the date in the required format
date "+%Y %B %d"

        Output sample  

        5) Set date and time
date -s "09 July 2023 11:11:11"

        Output sample

expand:

        Sometimes the program needs to calculate the time it takes to execute the code. This can be done through the date command. For example, if we want to calculate the execution time of a program fragment, we can write the following code:

start=$(date +%s)

#start和end中间这一段填写代码指令

sleep 5 # 延迟5s 

end=$(date +%s)
delta=$(( end - start))
echo -e "\nTime consumption is $delta seconds."

        Execution effect:

Guess you like

Origin blog.csdn.net/weixin_42839065/article/details/131620169