在 Ruby 中以这种格式 YYYYMM 获取当前年份和月份(和下个月)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10956240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:11:50  来源:igfitidea点击:

Get current year and month (and next month) in this format YYYYMM in Ruby

rubydatetime

提问by Hommer Smith

How do I get the current date and month in Ruby in a specific format?

如何以特定格式在 Ruby 中获取当前日期和月份?

If today is June, 8th of 2012, I want to get 201206.

如果今天是 2012 年 6 月 8 日,我想得到201206.

And also, I would like to be able to get the next month from the one we are in, taking into account that in 201212, the next month would be 201301.

而且,考虑到在201212 中,下个月将是201301,我希望能够从我们所在的月份获得下个月

回答by Michael Kohl

I'd do it like this:

我会这样做:

require 'date'
Date.today.strftime("%Y%m")
#=> "201206"
(Date.today>>1).strftime("%Y%m")
#=> "201207"

The advantage of Date#>>is that it automatically takes care of certain things for you:

Date#>>的优点是它会自动为您处理某些事情:

Date.new(2012,12,12)>>1
#=> #<Date: 2013-01-12 ((2456305j,0s,0n),+0s,2299161j)>

回答by Josh

Current month:

这个月:

date = Time.now.strftime("%Y%m")

Next month:

下个月:

if Time.now.month == 12
  date = Time.now.year.next.to_s + "01"
else
  date = Time.now.strftime("%Y%m").to_i + 1
end

回答by Amin Ariana

As of Ruby 2, "next_month" is a method on Date:

从 Ruby 2 开始,“next_month”是 Date 上的一个方法:

require "Date"

Date.today.strftime("%Y%m")
# => "201407"

Date.today.next_month.strftime("%Y%m")
# => "201408"

回答by Mahattam

require 'date'
d=Date.today                    #current date
d.strftime("%Y%m")              #current date in format
d.next_month.strftime("%Y%m")   #next month in format

回答by three

use http://strfti.me/for that kind of stuff

使用http://strfti.me/做那种东西

strftime "%Y%m"

回答by Wasim

Ruby 2 Plus and rails 4 plus.

Ruby 2 Plus 和 rails 4 plus。

By using below functions you can find required results.

通过使用以下功能,您可以找到所需的结果。

Time.now #current time according to server timezone
Date.today.strftime("%Y%m") # => "201803"

Date.today.next_month.strftime("%Y%m") # => "201804"