Compare date bash script


 
Thread Tools Search this Thread
Top Forums UNIX for Beginners Questions & Answers Compare date bash script
# 1  
Old 12-10-2019
Compare date bash script

I all
I have written a bash script for compare two date. One of those is a result of query, and another is current date.
I have a problem with the format, because the first is 09/12/19 18:50:30 but for having this result I have to do
Code:
 d1DB=$(date -d "$valData" +'%m/%d/%y %T')

and the second is 09/12/19 18:52:05
Code:
currenttime=$(date +'%d/%m/%y %T')

I want inform you that the first date is taken as string from DB, and after I convert it in date with parameter +'%m/%d/%y' and NOT +'%m/%d/%y' because I have month and day reverse

How I can resolve this problem of format?
How I can compare two date, so I can verify when the diff is more or less of 3 minutes?

Thanks a lot

Last edited by rbatte1; 12-10-2019 at 08:28 AM.. Reason: Added ICODE tags
# 2  
Old 12-10-2019
Personally, I always convert formatted time strings to a unix timestamp before doing time operations, and then covert the resulting time stamp back to a formatted time string if I need one.

Also, in all the databases I use on a regular basis, the dates and times are all stored as unix time stamps in the tables.

As an example, last week I wrote some code which estimated the load on the server and modified the DB queries based on the load and then calculated the estimated time to completion of that project in the log files, updated every minute. All the calculation were based on unix time stamp except the final log file entry, which I converted to my local time format for easy reading.

There are lot of people who will write code to do time operations on formatted time strings; but this is "a kludge" in my view, as time operations should be performed and stored as a unix time stamp and when a human wants to read the time, we then covert the time stamp to a local format based on the time zone of the user.

Also, let's say that you are in Brazil and your friend is in Japan. You want to do the same task at the same time (on a computer). It is best to specify the exact time as a unix time stamp, so you both will use the same time; and if you want to know the "formatted time" you can covert that time to a time string appropriate for your time zone.

Anyway.... that is my suggestion. That is what I always do...... all operations (processing) in unix timestamps.

YMMV
# 3  
Old 12-10-2019
Your two parameters (which I have wrapped in ICODE tags for you) appear to be the same to me. Notwithstanding, I'm wondering if the table column in question is a string or a date. The output of DESC your_table_name ; will should you what it is defined as. If it is stored as a date field, then we can probably adjust the SELECT statement.

Can you show us your table structure, the query and some sample output that we need to logically compare? The way to do it will be to convert it to Unix time (number of seconds since the Epoch, 1/1/1970) as Neo says, and then it is a simple subtraction.


Thanks, in advance,
Robin
# 4  
Old 12-10-2019
Thanks a lot for your suggest.
My table DESC is:
Code:
MariaDB [RaspyDB]> DESC TemperatureLOG;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| TimeLog | datetime    | NO   | MUL | NULL    |       |

My complete code is:
Code:
#!/bin/bash
source /var/www/script/QUERY/configLogin.cnf

DB_USER=$user >&2
DB=$DB >&2
DB_PASS=$pwd >&2
DB_IP=$IP >&2



query="select DATE_FORMAT(TimeLog, '%d/%m/%y %H:%i:%s') FROM TemperatureLOG order by TimeLog DESC LIMIT 1;"

tempVal=$(mysql -u "$DB_USER" --password="$DB_PASS" --host="$DB_IP" --database="$DB" --execute="$query" | awk 'NR==2{print $1,$2}')
echo "string  DB:$tempVal="


dataDB_tmp=${tempVal%% *}
echo "data_tmp DB:$dataDB_tmp"

d1DB=$(date -d "$tempVal" +'%m/%d/%y %T')
echo "data DB:$d1DB"

dataDB=$(date -d "$dataDB_tmp" +"%d/%m/%y");
echo "data DB:$dataDB"

timeDB=${tempVal##* }
echo "time DB:$timeDB"


currenttime=$(date +'%d/%m/%y %T')
echo "current time:$currenttime"

curDate=$(date +'%d/%m/%y')
echo "current data:$curDate"

curTime=$(date +'%T')
echo "current time:$curTime"
if [[ $D1db > $currenttime ]];
then
        echo "db minore current"
else
        echo "current maggiore db"
fi


echo $(( $currenttime - $D1db ))

val1=2013-12-31T00:00:00
val2=2014-11-19T15:40:30
if [[ $val1 < $val2 ]];
then
        echo $?
else
        echo $?
fi

echo $(( $val2 - $val1 )/(60*60*24))

below same test of query
Code:
MariaDB [RaspyDB]> select DATE_FORMAT(TimeLog, '%d/%m/%y %H:%i:%s') FROM TemperatureLOG order by TimeLog DESC LIMIT 1;
+-------------------------------------------+
| DATE_FORMAT(TimeLog, '%d/%m/%y %H:%i:%s') |
+-------------------------------------------+
| 10/12/19 14:21:40                         |
+-------------------------------------------+
1 row in set (0.01 sec)

MariaDB [RaspyDB]> select TimeLog FROM TemperatureLOG order by TimeLog DESC LIMIT 1;
+---------------------+
| TimeLog             |
+---------------------+
| 2019-12-10 14:23:41 |
+---------------------+
1 row in set (0.00 sec)

MariaDB [RaspyDB]>

# 5  
Old 12-10-2019
Yeah, that is your "problem"

You store the date and time as a formatted datetime string.

This creates a mess.

It is best to store all your dates (as I said) as an integer(11) not a string but since you are storing as a datetime string, that's OK... you can deal with this easily:

The first thing you need to do is to convert that datetime string to a unix timestamp, for example (like this):

Code:
query="select UNIX_TIMESTAMP( 'YOUR DATETIME STRING HERE') FROM TemperatureLOG order by TimeLog DESC LIMIT 1;"

I did not test it, but you get the idea. UNIX_TIMESTAMP() will take a formatted string and convert it to unix time.


Quote:
MySQL UNIX_TIMESTAMP() returns a Unix timestamp in seconds since '1970-01-01 00:00:00' UTC as an unsigned integer if no arguments are passed with UNIX_TIMESTAMP().

When this function is used with a date argument, it returns the value of the argument as an unsigned integer in seconds since '1970-01-01 00:00:00' UTC.

The argument may be a DATE, DATETIME,TIMESTAMP or a number in YYYYMMDD or YYMMDD.

Note: Since UNIX_TIMESTAMP() works on the current datetime, your output may vary from the output shown.

Syntax:

UNIX_TIMESTAMP(); UNIX_TIMESTAMP(date); UNIX_TIMESTAMP(datetime);
# 6  
Old 12-10-2019
Note, you can probably just do something like this:

Code:
query="select UNIX_TIMESTAMP(TimeLog) as mytime FROM TemperatureLOG order by mytime DESC LIMIT 1;"

# 7  
Old 12-10-2019
Thanks a lot
With your suggest I have this result
Code:
MariaDB [RaspyDB]> select UNIX_TIMESTAMP(TimeLog) as mytime FROM TemperatureLOG order by mytime DESC LIMIT 1;
+------------+
| mytime     |
+------------+
| 1575991329 |

Now I have to convert this value to date, correct? and after compare with current time
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Compare Date to today's date in shell script

Hi Community! Following on from this code in another thread: #!/bin/bash file_string=`/bin/cat date.txt | /usr/bin/awk '{print $5,$4,$7,$6,$8}'` file_date=`/bin/date -d "$file_string"` file_epoch=`/bin/date -d "$file_string" +%s` now_epoch=`/bin/date +%s` if then #let... (2 Replies)
Discussion started by: Greenage
2 Replies

2. UNIX for Beginners Questions & Answers

Bash script to compare file all the files exits or not

Currently i am building a script like based on region parameter it will filter the records in config file and then it will create a text file like ab.txt and it will read the path location in that file and now i need to compare the files name in the config file to files in the path of the config... (1 Reply)
Discussion started by: saranath
1 Replies

3. Shell Programming and Scripting

Array compare bash script

Hello, i have a script that should compare between ${ARRAY} that contains all fstab record like this : >>echo ${ARRAY} / /boot between all mountpoints in my df that is stord in ${ARRAY2} >>echo ${ARRAY2} / /boot /dev/shm /var/spool/asterisk/monitor now i have this loop: for i in... (6 Replies)
Discussion started by: batchenr
6 Replies

4. Shell Programming and Scripting

Bash script to compare 2 file

Hello Friends please help me to create script to compare 2 fiile which has rpm info . File 1: glibc-2.12.1.149.el6_6.5.x86_64.rpm glibc-common-2.12-1.149.el6_6.5.x86_64.rpm File 2 : glibc-2.12.123.el6_6.5.x86_64.rpm glibc-common-2.12-123.el6_6.5.x86_64.rpm To compare file1... (1 Reply)
Discussion started by: rnary
1 Replies

5. Shell Programming and Scripting

Shell script to compare two files of todays date and yesterday's date

hi all, How to compare two files whether they are same are not...? like i had my input files as 20141201_file.txt and 20141130_file2.txt how to compare the above files based on date .. like todays file and yesterdays file...? (4 Replies)
Discussion started by: hemanthsaikumar
4 Replies

6. Shell Programming and Scripting

Compare & Copy Directories : Bash Script Help

Beginner/Intermediate shell; comfortable in the command line. I have been looking for a solution to a backup problem. I need to compare Directory 1 to Directory 2 and copy all modified or new files/directories from Directory 1 to Directory 3. I need the directory and file structure to be... (4 Replies)
Discussion started by: Rod
4 Replies

7. Shell Programming and Scripting

Date Compare Script

Hi All, I wil be having Files as below in SourceFile_Path DIR AA.20110131 AA.20110228 AA.20110202 AA.20110330 BB.20091031 I want to Keep only monthly (20110131,20110228,20100229,20110330) in First SourceFile_Path, If it is not monthly file then want to Move files to some another... (5 Replies)
Discussion started by: samadhanpatil
5 Replies

8. Shell Programming and Scripting

Bash script to compare two lists

Hi, I do little bash scripting so sorry for my ignorance. How do I compare if the two variable not match and if they do not match run a command. I was thinking a for loop but then I need another for loop for the 2nd list and I do not think that would work as in the real world there could... (2 Replies)
Discussion started by: GermanJulian
2 Replies

9. Shell Programming and Scripting

How to compare time in bash script?

Hi, Anyone know how to compare the time in bash script? I want to compare say 30 min. to 45 min. ( AIX ) Thanks. (1 Reply)
Discussion started by: sumit30
1 Replies

10. Shell Programming and Scripting

count and compare no of records in bash shell script.

consider this as a csv file. H,0002,0002,20100218,17.25,P,barani D,1,2,3,4,5,6,7,8,9,10,11 D,1,2,3,4,5,6,7,8,9,10,11 D,1,2,3,4,5,6,7,8,9,10,11 D,1,2,3,4,5,6,7,8,9,10,11 D,1,2,3,4,5,6,7,8,9,10,11 T,5 N i want to read the csv file and count the number of rows that start with D and... (11 Replies)
Discussion started by: barani75
11 Replies
Login or Register to Ask a Question