Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last day of last month in unix

Tags:

date

unix

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

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

like image 485
sp_user123 Avatar asked Dec 26 '22 03:12

sp_user123


2 Answers

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.

like image 61
Kent Avatar answered Jan 21 '23 15:01

Kent


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

like image 24
fedorqui 'SO stop harming' Avatar answered Jan 21 '23 15:01

fedorqui 'SO stop harming'