Shell?中常用?Date?日期的計(jì)算
正文
在使用 Crontab 定時(shí)任務(wù)和 Shell 腳本切割 Nginx 日志文件時(shí),要用到時(shí)間戳、當(dāng)月、上月、下月、上月初、上月末、下月初、下月末等等,其中有些日期不能直接獲取,需要經(jīng)過(guò)一定的計(jì)算才能得到。
Shell Date
一、Date 基礎(chǔ)格式化
格式 | 輸出 | 含義 |
---|---|---|
date | 2022年 11月 15日 星期二 19:10:21 CST | 當(dāng)前日期和時(shí)間 |
date +%Y | 2022 | 年 |
date +%y | 22 | 年 |
date +%m | 11 | 月 |
date +%d | 15 | 日 |
date +%D | 11/15/22 | 當(dāng)前日期 |
date +%Y%m%d | 20221115 | 當(dāng)前日期 |
date +%F | 2022-11-15 | 當(dāng)前日期 |
date +%H | 19 | 時(shí) |
date +%M | 20 | 分 |
date +%S | 30 | 秒 |
date +%s | 1668511253 | 時(shí)間戳 |
date +%T | 19:21:26 | 時(shí)分秒 |
date +%H:%M:%S | 19:21:26 | 時(shí)分秒 |
date +%w | 2 | 今天是周二 |
date +%W | 46 | 今年的第46周 |
cal | (當(dāng)月日歷) | 當(dāng)月日歷 |
二、Date 日期計(jì)算
當(dāng)前日期:2022-11-15
- 前一天
date -d "-1 day" # 2022年 11月 14日 星期一 19:34:01 CST date -d "-1 day" +%F # 2022-11-14 date -d "last day" +%F # 2022-11-14
- 前三天
date -d "-3 day" +%F # 2022-11-12
- 后一天
date -d "1 day" +%F # 2022-11-16 date -d "next day" +%F # 2022-11-16
- 上一月
date -d "-1 month" +%F # 2022-10-15 date -d "last month" +%Y%m # 202210
- 下一月
date -d "1 month" +%F # 2022-12-15 date -d "next month" +%Y-%m # 2022-12
- 上一年
date -d "-1 years" +%F # 2021-11-15 date -d "last year" +%Y%m # 202111
- 時(shí)間戳轉(zhuǎn)日期
date -d @1621563928 # 2021年 05月 21日 星期五 10:25:28 CST
- 日期轉(zhuǎn)時(shí)間戳
date +%s -d "2022-10-21 10:38:48" # 1666319928
- 當(dāng)月末日期和當(dāng)月天數(shù):先獲取下個(gè)月第一天,減去一天
nextMonthStart=`date -d "${date} +1 month" "+%Y%m01"` currMonthEnd=`date -d "${nextMonthStart} -1 day" "+%F"` currMonthDays=`date -d "${nextMonthStart} -1 day" "+%d"` echo $currMonthEnd # 2022-11-30 echo currMonthDays # 30
以上就是Shell 中常用 Date 日期的計(jì)算的詳細(xì)內(nèi)容,更多關(guān)于Shell Date日期計(jì)算的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
PowerShell中運(yùn)行CMD命令的技巧總結(jié)(解決名稱沖突和特殊字符等問(wèn)題)
這篇文章主要介紹了PowerShell中運(yùn)行CMD命令的技巧總結(jié)(解決名稱沖突和特殊字符等問(wèn)題),需要的朋友可以參考下2014-05-05PowerShell查看本機(jī)文件關(guān)聯(lián)程序和默認(rèn)打開程序的方法
這篇文章主要介紹了PowerShell查看本機(jī)文件關(guān)聯(lián)程序和默認(rèn)打開程序的方法,本文給出了查看方法,同時(shí)給出了一份讀取結(jié)果,需要的朋友可以參考下2015-06-06Powershell Profiles配置文件的存放位置介紹
這篇文章主要介紹了Powershell Profiles配置文件的存放位置介紹,Profiles文件存放的位置不同,它的作用域也會(huì)不同,需要的朋友可以參考下2014-08-08PowerShell小技巧之獲取TCP響應(yīng)(類Telnet)
這篇文章主要介紹了使用PowerShell獲取TCP響應(yīng)(類Telnet)的小技巧,需要的朋友可以參考下2014-10-10