如何在红宝石中获得上个月的今天?

时间:2021-11-03 23:26:08

Is there a built-in function to get the day in last month, same as today? Examples:

是否有内置功能可以在上个月获得,与今天相同?例子:

2010/05/02 -> 2010/04/02
2010/05/15 -> 2010/04/15
2010/05/31 -> 2010/04/30

Thanks!

谢谢!

5 个解决方案

#1


11  

You can subtract entire months with <<.

你可以用< <减去整个月份。< p>

>> d = Date.parse('2010-05-31')
=> #<Date: 4910695/2,0,2299161>
>> d.to_s
=> "2010-05-31"
>> (d<<1).to_s
=> "2010-04-30"

More info

更多信息

#2


3  

You could do this:

你可以这样做:

(Date.today - 1.month).strftime("%Y/%m/%d")

#3


3  

You can try using

你可以尝试使用

Time.parse('2010/05/31').months_since(-1).

Time.parse( '2010/05/31')。months_since(-1)。

#4


1  

You could for instance make a time object

例如,您可以创建一个时间对象

old_time = Time.now

Then create a new time object based on that

然后基于此创建一个新的时间对象

new_time = Time.local(old_time.year, (old_time.month - 1), old_time.day, old_time.hour, old_time.min, old_time.sec)

However, as deceze pointed out, what is the criterion for 5/31 becoming 4/30? In irb, 4/31 'overflows' to 5/01.

然而,正如deceze指出的那样,5/31成为4/30的标准是什么?在irb,4/31'溢出'到5/01。

#5


0  

Ruby's date class allows you to add, subtract days from a particular date.

Ruby的日期类允许您添加,减去特定日期的天数。

#1


11  

You can subtract entire months with <<.

你可以用< <减去整个月份。< p>

>> d = Date.parse('2010-05-31')
=> #<Date: 4910695/2,0,2299161>
>> d.to_s
=> "2010-05-31"
>> (d<<1).to_s
=> "2010-04-30"

More info

更多信息

#2


3  

You could do this:

你可以这样做:

(Date.today - 1.month).strftime("%Y/%m/%d")

#3


3  

You can try using

你可以尝试使用

Time.parse('2010/05/31').months_since(-1).

Time.parse( '2010/05/31')。months_since(-1)。

#4


1  

You could for instance make a time object

例如,您可以创建一个时间对象

old_time = Time.now

Then create a new time object based on that

然后基于此创建一个新的时间对象

new_time = Time.local(old_time.year, (old_time.month - 1), old_time.day, old_time.hour, old_time.min, old_time.sec)

However, as deceze pointed out, what is the criterion for 5/31 becoming 4/30? In irb, 4/31 'overflows' to 5/01.

然而,正如deceze指出的那样,5/31成为4/30的标准是什么?在irb,4/31'溢出'到5/01。

#5


0  

Ruby's date class allows you to add, subtract days from a particular date.

Ruby的日期类允许您添加,减去特定日期的天数。