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.
Using dateutils' dround tool:
Current month:
$ dround today -1
2014-02-01
Previous month
$ dround today -31
2014-01-31
Last day of current month:
$ dround today +31
2014-02-28
Of course you can use a custom date instead of today
, the idea is to round down or up to the desired day-of-the month, e.g. the next first-of-the-month given 2010-10-04:
$ dround 2010-10-04 +1d
2010-11-01
$ date +%m/01/%Y
I came here looking for a way to get the first day of the current month.
As you're using Linux, hhopefully you have the GNU date utility available. It can handle almost any description of a relative date that you think of.
Here are some examples
date --date="last month" +%Y-%m-%d
date --date="yesterday" +%Y-%m-%d
date --date="last month" +%b
x=$(date --date "10 days ago" +%Y/%m/%d)
To learn more about it see GNU Date examples
Once you use it some, you can shortcut your information gathering with date --help
, which shows all the basic options (but is sometimes is hard to interpret.)
I hope this helps.
This is going to be convoluted in a shell script. You are better off using Date::Manip in perl, or something similar in another full-featured language. However, I can think of some ways to do this with the date command. First of all, you can use a --date parameter to set a starting point for date, like so:
$ date --date='08-JUN-2011' Wed Jun 8 00:00:00 EDT 2011
You can get the previous date like this:
$ date --date='08-JUN-2011 -1 days' Tue Jun 7 00:00:00 EDT 2011
For the last day of the month, I would just walking back from 31 until date does not fail. You can check $? for that
$ date --date='31-JUN-2011';echo $? date: invalid date `31-JUN-2011' 1 $ date --date='30-JUN-2011';echo $? Thu Jun 30 00:00:00 EDT 2011 0
For the first day of the month...that is usually 01 :)
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