I have start date and end date in the following format. I need to check the current date is greater than the start date and less than the end date. if i use the command date --date "Tue 6:00 AM", it takes next Tues day not the current week's Tues day. Is there a way to get the current Tues day?
start date-end date
Tue 6:00 AM-Wed 10:00 PM
No. I need to check the current date is between the start date or not. If i run the command with 1 week ago, the start date will be Tue Nov 2 06:00:00 EDT 2010
but End date will be Wed Oct 27 22:00:00 EDT 2010 which wrong. I hope that i am making you clear.
#!/bin/ksh
# Works only with GNU date
d1="Tue Nov 02 22:00:00 EDT 2010"
d2="Fri Nov 05 22:00:00 EDT 2010"
cdate=$(date)
dat1=$(date +%s -d "$d1")
dat2=$(date +%s -d "$d2")
curr=$(date +%s -d "$cdate")
if [ $curr -gt $dat1 -a $curr -lt $dat2 ]
then
echo Current date is between "$d1" and "$d2"
fi
How about replace Tue (current day) with blank giving "6:00am":
START="Tue 6:00 AM"
END="Wed 10:00 PM"
DOW=$(date +%a)
START=${START/$DOW/}
END=${$END/$DOW/}
NOW=$(date +%s)
if [ $NOW -ge $(date --date $START +%s) -a $NOW -le $(date --date $END +%s) ]
then
# Your code here
fi
I know if today is Thursday the compare is with next weeks dates, but that's fine as result (not within range) is still what you want.
--- Edit----
But my solution still dosn't work for Mon 8:00AM-Thu 9:00PM, problem is you can't apply the DOW modifiers to any date except the current date.
What we need is date --date "Monday 9:00AM from 6 days ago"
OK here is a bash/ksh script that does it (again you need GUN date for the --date function).
I defined a function thisweek() that returns the epoch time of a string like "Tue 09:00AM", once that's done the rest is a simple numeric comparison.
inrange:
DOW_TODAY=$(date +%u)
thisweek()
{
DOW=$(date --date "$1" +%u)
[ $DOW -lt $DOW_TODAY ] && date --date "${1}-7days" +%s && return
date --date "${1}" +%s
}
END=${1#*-}
START=${1%-*}
NOW=$(date +%s)
if [ $NOW -ge $(thisweek $START) -a $NOW -le $(thisweek $END) ]
then
echo "In range"
else
echo "Not in range"
fi
Here are some tests:
$ inrange "Mon 01:00AM-Fri 09:00PM"
In range
$ inrange "Mon 01:00AM-Tue 01:00AM"
Not in range
$ inrange "Thu 11:00PM-Fri 11:00PM"
Not in range
$ inrange "Yesterday 11PM-3PM"
In range