sp_user123
sp_user123

Reputation: 502

How to get last day of last month in unix

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

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

Upvotes: 4

Views: 26461

Answers (6)

10hero
10hero

Reputation: 15

echo $(date -d "$(date +%d) days ago" +%F)

will give the last day of the last month.

Upvotes: 1

Brad Pitcher
Brad Pitcher

Reputation: 1785

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

Upvotes: 0

user2355675
user2355675

Reputation: 21

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.

Upvotes: 2

vissu
vissu

Reputation: 11

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

Upvotes: 0

Kent
Kent

Reputation: 195079

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.

Upvotes: 6

fedorqui
fedorqui

Reputation: 289735

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

Upvotes: 2

Related Questions