1 Commonly used time domains
% Y year (eg: 1970, 2018, etc.)
% y year (eg: 70, 18, etc.)
% m month (01..12)
% d day of the month (01..31)
% H hours (00..23)
% M points (00..59)
% S seconds (00..59)
2 date command
Use the date command without parameters to get the current time and date. The time obtained in this way is generally the time in the CST standard format.
To get a specific format, the command is: date + 'format', note that this is case sensitive.
Get yesterday's date. The -d option can be added to the above command.
Get the previous hour of the current time
Get the day before the specified date. This is actually asking for relative time. For example, the following is the date of the day before the National Day:
Convert Date to Timestamp Timestamp
convert timestamp back to date
Convert a timestamp to a date and display it in a specific format
Summarize:
[root@localhost:~]# date
Sun Jun 26 10:22:59 CST 2022
[root@localhost:~]# date +'%Y-%m-%d'
2022-06-26
[root@localhost:~]# date +'%Y/%m/%d %H:%M:%S'
2022/06/26 10:23:50
[root@localhost:~]# date +'%y/%m/%d %H:%M:%S'
22/06/26 10:24:22
[root@localhost:~]# date -d 'yesterday' +'%Y/%m/%d %H:%M:%S'
2022/06/25 10:24:44
[root@localhost:~]# date -d 'today -1 day' +'%Y-%m-%d'
2022-06-25
[root@localhost:~]# date -d 'today -1 hour' +'%Y%m%d%H'
2022062609
[root@localhost:~]# date +'%Y-%m-%d %H:%M:%S' -d '-1 hours'
2022-06-26 09:25:41
[root@localhost:~]# date -d '20221001 -1 day' +'%Y%m%d'
20220930
[root@localhost:~]# date -d "Sun Jun 26 10:22:59 CST 2022" +%s
1656210179
[root@localhost:~]# date -d @1656210179
Sun Jun 26 10:22:59 CST 2022
[root@localhost:~]# date -d @1656210179 +'%Y%m%d %H:%M:%S'
20220626 10:22:59
3 Modify server time
3.1 Manually modify the server time
Advantages: simple and easy to modify
Disadvantage: When the server is restarted, the server time will be reset according to the time zone
- date # View the current time
- date -s '2022-06-26 09:35:00' #Modification time is: 2022-06-26 09:35:00
3.2 Modify the time zone configuration file
Advantages: Because the modification is the configuration file, it is once and for all
- rm -rf /etc/localtime #Delete the configuration file of the current default time zone, it is not recommended to delete it directly (for operational security reasons), it is best to use the mv command to rename
- ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime #Create a soft link file to the configuration file area, replace the previously deleted or backed up /etc/localtime file
3.3 Command to modify time zone
Advantages: It will not fail after the server restarts, and this command will directly modify the configuration file.
- timedatectl #View the current time zone
- timedatectl set-timezone Asia/Shanghai #Set the current time zone to Shanghai