Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a date HH: MM: SS in second with bash?

Tags:

date

bash

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.

like image 492
MaxGeneGrim Avatar asked May 07 '13 08:05

MaxGeneGrim


People also ask

How do I convert dates to seconds in bash?

The command date +%S will print the current amount of seconds. What is the bash script you are using this in?

How do I convert a date to another format in bash?

Bash Date format MM-DD-YYYY To format date in MM-DD-YYYY format, use the command date +%m-%d-%Y or printf "%(%m-%d-%Y)T\n" $EPOCHSECONDS .

How do I echo date and time in bash?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...

What is date +% s in bash?

date +%S. Displays seconds [00-59] date +%N. Displays in Nanoseconds.


2 Answers

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

like image 67
Kent Avatar answered Nov 15 '22 17:11

Kent


On a Mac 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.

like image 43
Erik van Oosten Avatar answered Nov 15 '22 18:11

Erik van Oosten