Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I echo minutes since midnight in any timezone using the date command on OS X?

Here's what isn't working:

> echo $(( ($(date +%s) - $(date +%s -d$(date +%Y-%m-%d))) / 60 ))
date: illegal time format
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
            [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

I've also tried:

> echo $(date +%s -f%Y-%m-%d $(date +%Y-%m-%d))

The following works, but only with a fixed UTC offset that will break during standard time:

> echo $[ ( ( $(date "+%s") - 28800 ) % 86400 ) / 60 ]

Reference: OS X date manual

like image 532
Ryan Avatar asked Sep 12 '25 22:09

Ryan


1 Answers

The number of minutes (or seconds) since midnight can be computed directly from a time alone.

echo $(( $(date "+10#%H * 60 + 10#%M") ))  # Minutes since midnight
echo $(( $(date "+(10#%H * 60 + 10#%M) * 60 + 10#%S") ))  # Seconds since midnight

Note that this requires only minimal support from date, so will work with either GNU or BSD date.

This works by having date output a string which can be passed directly to the shell's arithmetic expression construct.

Thanks to Petesh for pointing out the need to force numbers with leading zeros to be treated as decimal.

like image 186
chepner Avatar answered Sep 15 '25 11:09

chepner