How to convert strings like “19-FEB-12” to epoch date in UNIX

大憨熊 提交于 2019-11-29 01:09:06
Anew

To convert a date to seconds since the epoch:

date --date="19-FEB-12" +%s

Current epoch:

date +%s

So, since your dates are in the past:

NOW=`date +%s`
THEN=`date --date="19-FEB-12" +%s`

let DIFF=$NOW-$THEN
echo "The difference is: $DIFF"

Using BSD's date command, you would need

$ date -j -f "%d-%B-%y" 19-FEB-12 +%s

Differences from GNU date:

  1. -j prevents date from trying to set the clock
  2. The input format must be explicitly set with -f
  3. The input date is a regular argument, not an option (viz. -d)
  4. When no time is specified with the date, use the current time instead of midnight.

Here's one way using GNU awk. To run:

awk -f script.awk file

Contents of script.awk:

BEGIN {

    n = systime()

    FS="-"
}

{
    t = mktime(sprintf("%d %d %d %d %d %d", "20" $3, convert($2), $1, 0, 0, 0))    

    printf "%.1f days ago\n", (n - t) / 60 / 60 / 24
}

function convert(m) {

    return(((index("JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC", m) - 1) / 3) + 1)
}

Results:

358.6 days ago
361.6 days ago
1286.6 days ago
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!