Search code examples
bashdatetimeepoch

Convert today's HH:MM am/pm to epoch in Bash


I have two variables $sunrise="7:23 am" and $sunset="6:10 pm". I need to convert both of them to today's epoch equivalent as in:

secSunrise=($date ... "$sunrise" ... +"%s")
secSunset=$(date ... "$sunset" ... +"%s")

The only thing I've figured out so far is doing it with current date-time:

$ secNow=$(date +"%s")
$ echo $secNow
1488331535

How to square this circle and plug the HH:MM am/pm 12-hour formatted variable into the date command?


Solution

  • You could use GNU date this way:

    date --date="7:23 am today" +%s
    # output => 1488352980
    
    date --date="6:10 pm today" +%s
    # output => 1488391800
    
    • %s prints epoch

    From man date:

    The --date=STRING is a mostly free format human readable date string such as "Sun, 29 Feb 2004 16:21:42 -0800" or "2004-02-29 16:21:42" or even "next Thursday". A date string may contain items indicating calendar date, time of day, time zone, day of week, relative time, relative date, and numbers. An empty string indicates the beginning of the day. The date string format is more complex than is easily documented here but is fully described in the info documentation.