Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the EPOCH time for a custom date values in bash

Tags:

bash

I need to write a bash function to return the EPOCH time for a custom date, in the future.

I use date and time in the formats;

date=20130122 # i.e. 2013 01 22
time=1455     # i.e. 14:55

Can I get the EPOCH time with these values?

Does anyone know a solution?

like image 275
lukegjpotter Avatar asked Dec 01 '22 04:12

lukegjpotter


2 Answers

date -d "$date $time" +%s

Would work in GNU date.

For BSD date (included with Mac OS X), the command would be

date -j -f "%Y%m%d %H%M" "$date $time" +%s

(-f is needed to parse your date and time as given; the default format would require "012214552013" to specify the same time)

like image 153
Hari Menon Avatar answered Dec 06 '22 07:12

Hari Menon


Short answer:

date --date "20130122 1455" +%s

This will give you the date in epoch.

Or if you use variables, just replace the date and time like this:

d=20130122
t=1455
date --date "$d $t" +%s

And try to avoid using "date" and "time" as variable names, since they easily could be misunderstood as commands (they are both valid commands). This to increase readability.

like image 39
Eigir Avatar answered Dec 06 '22 08:12

Eigir