【问题标题】:how to find the difference b/w to dates stored in a variable in shell script ( KSH shell )如何找到存储在 shell 脚本(KSH shell)变量中的日期的黑白差异
【发布时间】:2013-04-20 04:59:20
【问题描述】:

在 hp-ux 中,因为没有可用的 GNU date,即 date 命令的 -d-s 选项不可用。我如何找到两个给定日期之间的差异(就像我们在 Solaris 或 bash shell 中所做的那样)?

【问题讨论】:

  • 日期的格式是什么?
  • 它们的格式为 dd/mm/yyyy
  • 你想要几十年/月/小时/微秒的差异......?您需要更具体地了解您正在尝试做的事情。
  • 我想要天的差异。

标签: shell ksh hp-ux


【解决方案1】:

实际上可以通过 Google 找到许多解决方案,但 here 是我刚刚偶然发现的一种解决方案,并且喜欢它的简洁性。您可以在两个日期上使用它的ansi_dn 函数并计算差值。

diff_dates.sh:

#!/bin/ksh

. ./ansi_dn.sh

date_to="$1"
date_from="$2"

echo $((
      $(ansi_dn \
        $(echo "${date_to}"   | cut -d/ -f3) \
        $(echo "${date_to}"   | cut -d/ -f2) \
        $(echo "${date_to}"   | cut -d/ -f1) \
      )
    - $(ansi_dn \
        $(echo "${date_from}" | cut -d/ -f3) \
        $(echo "${date_from}" | cut -d/ -f2) \
        $(echo "${date_from}" | cut -d/ -f1) \
      )
))

(如果您已经将两个日期的年、月和日放在单独的变量中,那么显然不需要cut 噩梦。)

例子:

$ ./diff_dates.sh 08/05/2013 01/01/1939
27156

让我们用 GNU date 验证正确性:

$ echo $(( ( $(date -d 2013-05-08 +%s) - $(date -d 1939-01-01 +%s) + 43200 ) / 86400))
27156

【讨论】:

  • 但是上面代码中脚本 ansi_dn.sh 的内容是什么
  • @KVR_GROUPS:我在第一句话中链接到的函数,在这个答案中找到:unix.stackexchange.com/a/42415/36514
  • 你能解释一下吗?
  • 具体解释一下?您复制我链接到您的脚本的函数并像我在回答中显示的那样调用它。
  • 你能说一下它到底在做什么,因为我不理解那些奇怪的代码行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
相关资源
最近更新 更多