Linux Script- Date Manipulations

linuxscriptingshell

I will set one date variable(Say '08-JUN-2011') and I want to do some calculations based on that date namely,
1. Have to get the first day of the given day's month.
2. Previous date of the given date's month.
3. Last day of the given date's month.

All I know is manipulating using the current system date and time but don't know how to implement with user defined date. I need this to be achieved using Linux shell script.

Any help will be appreciated.

Thanks,
Karthik

Best Answer

Here's how to perform the manipulations using GNU date:

#!/bin/sh

USER_DATE=JUN-08-2011

# first day of the month
FIRST_DAY_OF_MONTH=$(date -d "$USER_DATE" +%b-01-%Y)

PREVIOUS_DAY=$(date -d "$USER_DATE -1 days" +%b-%d-%Y)

# last day of the month
FIRST_DAY_NEXT_MONTH=$(date -d "$USER_DATE +1 month" +%b-01-%Y)
LAST_DAY_OF_MONTH=$(date -d "$FIRST_DAY_NEXT_MONTH -1 day" +%b-%d-%Y)

echo "User date: $USER_DATE"
echo "1. First day of the month: $FIRST_DAY_OF_MONTH"
echo "2. Previous day: $PREVIOUS_DAY"
echo "3. Last day of the month: $LAST_DAY_OF_MONTH"

The output is:

User date: JUN-08-2011
1. First day of the month: Jun-01-2011
2. Previous day: Jun-07-2011
3. Last day of the month: Jun-30-2011