I'm trying to compare a date given by a user to a date in a file, basically a text file with lots of dates and times listed.
for example the user would enter a date such as 22/08/2007 and a time of 1:00, what i need the script to do is count how many dates in the text file are after the date given by the user.
I’ve managed to accomplish this by converting each date in the text file to unix timestamp and then comparing the two. Is there no way of simply comparing two dates in bash?
Thanks in advance
To compare two date strings:Pass the strings to the Date() constructor to create 2 Date objects. Compare the output from calling the getTime() method on the dates.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command.
The GNU date command can convert a date into the number of seconds since 1970. Try this script:
#! /bin/bash DATE=$(date -d "$3-$2-$1 01" '+%s') COUNT=0 tr '/' ' ' | { while read D M Y ; do THIS=$(date -d "$Y-$M-$D 01" '+%s') if (( THIS > DATE )) ; then COUNT=$((COUNT + 1)) fi done echo $COUNT }
It expects three arguments and the raw dates in stdin:
for D in $(seq 19 25) ; do echo $D/08/2007 ; done | ./count.sh 22 08 2007 3
It will work till 2038. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With