Monday, September 7, 2015

epoch when your date(1) doesn't understand +%s


10# given to force base 10, bash will attempt to be clever on zero-led numbers whereas ksh always assumes base 10.

toepoch() {
  local -i Y=10#${1:?} m=10#${2:?} d=10#${3:?} H=10#${4:?} M=10#${5:?} S=10#${6:?}

  if ((m > 2)); then
    let m-=3
  else
    let m+=9
    let --Y
  fi

  local -i c='Y / 100'
  local -i ya='Y - 100 * c'

  local -i j='
    (146097 * c)  / 4 +
    (1461 * ya)   / 4 +
    (153 * m + 2) / 5 +
    d'
  local -i result='((j - 719469) * 86400) + (H * 3600) + (M * 60) + S'

  echo $result
}

Can be then run as: toepoch $(date -u "+%Y %m %d %H %M %S")

No comments: