Reputation: 1
I'm trying to compare date between 2 date ranges
currentdate= curl -s "http://worldtimeapi.org/api/timezone/Asia/Jerusalem" | jq . | jq '.utc_datetime'
if [ "$currentdate" -ge "2020-10-28T10:00:00:00" && "$currentdate" -le "2020-11-10T10:00:00:00"]
then echo "between 10 days range dates"
fi
echo "not between 10 days range dates"
Upvotes: 0
Views: 124
Reputation: 2045
You can do the whole thing in jq if you want.
begin_date="2020-10-28T10:00:00Z"
end_date="2020-11-10T10:00:00Z"
curl -s "http://worldtimeapi.org/api/timezone/Asia/Jerusalem" | \
jq --arg bd $begin_date --arg ed $end_date '.unixtime
| if . >= ($bd | fromdate) and . <= ($ed | fromdate)
then "between 10 days range dates"
else "not between 10 days range dates"
end'
fromdate
converts the beginning and end dates into the number of seconds since the Unix epoch (1970-01-01T00:00:00Z). We can compare those numbers with the value of .unixtime.
I altered the beginning and end dates to a format that jq could easily recognize.
Note: in your original program, you only need to invoke jq once: jq '.utc_datetime'
would work.
Upvotes: 1
Reputation: 247042
-ge
and -le
are numeric comparison operators. Since you're using that ISO date format, you can compare the dates as strings:
date1="2020-10-28T10:00:00:00"
date2="2020-11-10T10:00:00:00"
if [[ "$date1" <= "$currentdate" && "$currentdate" <= "$date2" ]]; ...
Upvotes: 1
Reputation: 19625
Multiple ways to get current date to compare:
#!/usr/bin/env bash
# The needlessly complex way
curdate=$(
date -d "$(
curl -s "http://worldtimeapi.org/api/timezone/Asia/Jerusalem" |
jq -j .utc_datetime
)" +%s
)
# The shorter, but still POSIX shell way
curdate=$(date +%s)
# The most efficient Bash 4.2+ way
printf -v curdate '%(%s)T'
#mindate=$(date -d "2020-10-28T10:00:00" +%s)
mindate=1603875600
#maxdate=$(date -d "(@$mindate) + 10 days" +%s)
maxdate=1603929600
if [ $curdate -ge $mindate ] && [ $curdate -le $maxdate ]
then
echo "between 10 days range dates"
else
echo "not between 10 days range dates"
fi
Upvotes: 1
Reputation: 12887
You would need to format the dates into "seconds since 1970-01-01 00:00:00 UTC" for this. So first format the date by only taking the first 19 characters and then running that through date with -d and formatting with %s
currentdate=$(curl -s "http://worldtimeapi.org/api/timezone/Asia/Jerusalem" | jq . | jq '.utc_datetime')
if [[ "$(date -d ${currentdate:1:19} +%s)" -ge "$(date -d "2020-10-28T10:00:00" +%s)" && "$(date -d ${currentdate:1:19} +%s)" -le "$(date -d "2020-10-28T10:00:00" +%s)" ]]
then
echo "between 10 days range dates"
else
echo "not between 10 days range dates"
fi
Upvotes: -1