使用`date`命令获取上个月、当前和下个月 [英] Using `date` command to get previous, current and next month

查看:53
本文介绍了使用`date`命令获取上个月、当前和下个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Ubuntu 11.04 下使用下面获取上个月、当前和下个月:

I am using below to get previous, current and the next month under Ubuntu 11.04:

LAST_MONTH=`date +'%m' -d 'last month'`
NEXT_MONTH=`date +'%m' -d 'next month'`
THIS_MONTH=`date +'%m' -d 'now'`

直到今天,也就是 2012 年 10 月的最后一天 (2012-10-31)

It works well until today, the last day of October, 2012 (2012-10-31)

我现在得到以下结果:

$ date
Wed Oct 31 15:35:26 PDT 2012
$ date +'%m' -d 'last month'
10
$ date +'%m' -d 'now'
10
$ $ date +'%m' -d 'next month'
12

我想输出应该分别是 9,10,11.

I suppose the outputs should be 9,10,11 respectively.

不明白为什么 date 输出会这样.什么是让 previouscurrentnext 保持一致的好方法?

Don't understand why date outputs behave like this. What should be a good way to get consistant previous, current and next month instead?

推荐答案

问题在于 date 从字面上理解您的请求并尝试使用 9 月 31 日的日期(即 10 月 31 日减去一个月) 然后因为它不存在它移动到第二天存在.date 文档(来自 info date)有以下建议:

The problem is that date takes your request quite literally and tries to use a date of 31st September (being 31st October minus one month) and then because that doesn't exist it moves to the next day which does. The date documentation (from info date) has the following advice:

单位中的模糊可能会导致相关项目出现问题.为了例如,2003-07-31 -1 月"可能计算为 2003-07-01,因为2003-06-31 是无效日期.确定上个月更多可靠地,您可以要求当前的 15 号之前的一个月月.例如:

The fuzz in units can cause problems with relative items. For example, `2003-07-31 -1 month' might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:

 $ date -R
 Thu, 31 Jul 2003 13:02:39 -0700
 $ date --date='-1 month' +'Last month was %B?'
 Last month was July?
 $ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'
 Last month was June!

这篇关于使用`date`命令获取上个月、当前和下个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆