How to convert a date HH: MM: SS in second with bash?
Knowing that this is a date that I recovered in a file so I can't take it in another format.
I have two variables $DateStart and $DateEnd and i would like the difference between both.
How to convert a date HH: MM: SS in second with bash?
Knowing that this is a date that I recovered in a file so I can't take it in another format.
I have two variables $DateStart and $DateEnd and i would like the difference between both.
date +%s
returns the current datetime in seconds since 1970-01-01 00:00:00 UTC
if you want to get a given datetime in seconds since 1970-01-01 00:00:00 UTC, for example:
kent$ date -d"2008-08-08 20:20:20" +%s
1218219620
to get diff in seconds, you just get the two dates in seconds, and do a s1-s2
On a Mac (and probably other BSDs) you can convert a date into another date with a combination of the -j
and -f
option:
$ date -j -f '%Y-%m-%d %H:%M:%S' "2016-02-22 20:22:14" '+%s'
1456168934
Where -j
suppresses changing the system clock,
-f <fmt>
gives the format to use for parsing the given date,
"2016-02-22 20:22:14"
is the input date and
+<fmt>
is the output format.
Assuming the time in HH:MM:SS format is in variable time_hhmmss
and time in
seconds needs to be stored in time_s
:
IFS=: read -r h m s <<<"$time_hhmmss"
time_s=$(((h * 60 + m) * 60 + s))
Try to use my solution with sed+awk:
echo $DateStart | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}'
echo $DateEnd | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}'
it splits the string with sed, then inverts the numbers backwards ("DD hh mm ss" -> "ss mm hh DD") and calculates them with awk. It works even you add days: [[DD-]hh:]mm:ss, eg:
34:56 12:34:56 123-12:34:56
When using the above examples remember to add -u (to use GMT) otherwise 1970-01-01 00:00:00 is not zero :-)
$ date -d"1970-01-01 00:00:00" +%s
-3600
$ date -u -d"1970-01-01 00:00:00" +%s
0
© 2022 - 2024 — McMap. All rights reserved.
date
should still be supplied with them. Otherwise, if only times are passed,date
will assume today and times calculated on either side of midnight will have additional 24 hour difference between them. – Yetac