How to get last day of last month in unix

2020-03-24 07:10发布

I have the requirement to get the last date of the last month.

For today the last months last day is 30 (April).

标签: unix date
5条回答
▲ chillily
2楼-- · 2020-03-24 07:47

this should work if you have gnu date:

1 day ago <month> 1

<month> here is current month, for example

kent$  date -d'1 day ago may 1' 
Tue Apr 30 00:00:00 CEST 2013

another example, find the last day of the month before July:

kent$  date -d'1 day ago july 1'
Sun Jun 30 00:00:00 CEST 2013

note that, the timestamp was set to 00:00:00.

查看更多
干净又极端
3楼-- · 2020-03-24 07:48
m=`date +%m`
set -A mth Dec Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
prevmth=${mth[$((m - 1))]}


echo $prevmth
查看更多
做个烂人
4楼-- · 2020-03-24 08:01

My comment date -d 'last month' was wrong.

This works:

date -d "-$(date +%d) days -0 month"

Test

Just changed my date to test this way:

$ date
Web May 29 14:06:36 CEST 2013
$ date -d "-$(date +%d) days -0 month"
Tue Apr 30 14:06:36 CEST 2013

Reference: http://databobjr.blogspot.nl/2011/06/get-first-and-last-day-of-month-in-bash.html

查看更多
闹够了就滚
5楼-- · 2020-03-24 08:04
date -d "$(date +%Y-%m-01) -1 day"

It means "Show me the date that is the 1st of the current month minus 1 day"

EDIT:

For MacOS, the args are a bit different

date -v-1d +%Y-%m-%d
查看更多
Root(大扎)
6楼-- · 2020-03-24 08:10

For KSH/BASH

y=$(date '+%Y') # Get current year
m=$(date '+%m') # Get current month
((m--))         # Decrement month
[[ ${m} == 0 ]] && ((y--)) # If month zero, decrement year
[[ ${m} == 0 ]] && m=12    # If month zero, reset to 12

cal ${m} ${y} | awk 'NF{A=$NF}END{print A}'  
# Run cal, and print the last field of the last line with fields.
查看更多
登录 后发表回答