macos - 在 Mac OS X shell 脚本中从开始日期循环到结束日期

标签 macos bash shell date

OS X (Snow Leopard) 上的日期函数没有像 GNU 版本那样的 --date 选项,我无法弄清楚如何在 OS X 上获得以下等效项:

startdate=2010-01-01
enddate=2010-01-31
foldate="$startdate"

until [ "$foldate" == "$enddate" ]
do
    # do something with the date here - like pass it as a parameter to a command
    foldate=`/bin/date --date "$foldate 1 day" +%Y-%m-%d`
done

解决了 SiegeX 的回答:

startdate=2010-01-01
enddate=2010-01-31

sDateTs=`date -j -f "%Y-%m-%d" $startdate "+%s"`
eDateTs=`date -j -f "%Y-%m-%d" $enddate "+%s"`
dateTs=$sDateTs
offset=86400

while [ "$dateTs" -le "$eDateTs" ]
do
  date=`date -j -f "%s" $dateTs "+%Y-%m-%d"`
  printf '%s\n' $date
  dateTs=$(($dateTs+$offset))
done

最佳答案

通过运行 man date 阅读你的日期的联机帮助页并查看 -v 选项。以下是摘录:

-v Adjust (i.e., take the current date and display the result of the adjustment; not actually set the date) the second, minute, hour, month day, week day, month or year according to val. If val is preceded with a plus or minus sign, the date is adjusted forwards or backwards according to the remaining string, otherwise the relevant part of the date is set. The date can be adjusted as many times as required using these flags. Flags are processed in the order given.

关于macos - 在 Mac OS X shell 脚本中从开始日期循环到结束日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4434782/

相关文章:

创建我自己的 shell 。处理 Ctrl-Z 然后发送 SIGCONT 关闭进程而不是继续它

objective-c - 如何创建自定义 NSMenuItem

linux - OSX shell 脚本打开新的终端窗口并运行程序

linux - AWK 根据其他列的 if else 写入新列

linux - 删除列 csv 文件,其中一些包含引号文本(包括逗号)

ruby-on-rails - Docker - 无法转发交互式 shell 的端口

cocoa - 如何将 NSImage 保存为新文件

ios - Swift 中忽略大小写和变音符号的正则表达式匹配范围

bash - 在 bash 中可以使用纳秒级的 strftime 吗?

linux - 如果在一行中找到大写字母则拆分行