Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Script- Date Manipulations

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

like image 594
Karthik Avatar asked Jun 10 '11 12:06

Karthik


People also ask

How do I change the date format in Unix shell script?

To format date in YYYY-MM-DD format, use the command date +%F or printf "%(%F)T\n" $EPOCHSECONDS . The %F option is an alias for %Y-%m-%d . This format is the ISO 8601 format.


1 Answers

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
like image 113
Gregg Avatar answered Sep 19 '22 16:09

Gregg