Linux Command “date” หาวัน
ในภาษา programing ต่าง ๆ ในการหาวัน เช่น วันที่ผ่านมาแล้ว 90 วัน จะเป็นวันอะไร เราอาจจะใช้เทคนิคหาโดยแปลง gregorian/julian date เพื่อหาวันที่ต้องการ
แต่ถ้าใน shell linux นั้นไม่มีคำสั่งการแปลง gregorian/julian date มาให้ แต่ในคำสั่ง date นั้นมีวิธีที่ง่ายกว่านั้น นั่นคือใช้คำสั่ง date -d “expression string” โดยเงื่อนไขเป็น day/month/year หากต้องการหาวันย้อนหลังให้ใส่ ago เพิ่มไป เช่น
# วันปัจจุบัน mmddyy
$ date ‘+%m%d%y’
110921
# หาวันล่วงหน้าจากปัจจุบัน 2 วัน
$ date -d “2 day” ‘+%m%d%y’
111121
$ date -d “2 days” ‘+%m%d%y’
111121
#หาวันย้อนหลังจากปัจจุบัน 2 วัน
$ date -d “2 day ago” ‘+%m%d%y’
110721
$ date -d “2 days ago” ‘+%m%d%y’
110721
#หาวันย้อนหลังจากปัจจุบัน 2 ปี
$ date -d “2 years ago” ‘+%m%d%y’
110919
$ date -d “2 year ago” ‘+%m%d%y’
110919
Note: ดูคำอธิบายเพิ่มเติมของ date โดยสั่ง
$ info date
จะมีคำอธิบายเพิ่มเติมจากคำสั่ง “man date”
ตัวอย่างการใช้ date จะอยู่ที่หัวข้อ 21.1.7
21.1.7 Examples of ‘date’
— — — — — — — — — — — — -
Here are a few examples. Also see the documentation for the ‘-d’ option
in the previous section.
• To print the date of the day before yesterday:
date -- date=’2 days ago’
• To print the date of the day three months and one day hence:
date -- date=’3 months 1 day’
• To print the day of year of Christmas in the current year:
date -- date=’25 Dec’ +%j
But this may not be what you want because for the first nine days
of the month, the ‘%d’ expands to a zero-padded two-digit field,
for example ‘date -d 1may ‘+%B %d’’ will print ‘May 01’.
• To print a date without the leading zero for one-digit days of the
month, you can use the (GNU extension) ‘-’ flag to suppress the
padding altogether:
date -d 1may ‘+%B %-d’
• To print the current date and time in the format required by many
non-GNU versions of ‘date’ when setting the system clock:
date +%m%d%H%M%Y.%S
• To set the system clock forward by two minutes:
date — set=’+2 minutes’