【问题标题】:Get current year and month (and next month) in this format YYYYMM in Ruby在Ruby中以这种格式YYYYMM获取当前年份和月份(以及下个月)
【发布时间】:2012-06-12 22:47:12
【问题描述】:

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

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

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

【问题讨论】:

  • 谷歌时间#strftime
  • tokland 我知道我可以做到这一点 Time.now.strftime("%Y%m") - 但是下个月我如何获得?
  • 我编辑了我的答案以反映您的编辑。它现在会生成您想要的日期。

标签: ruby date time


【解决方案1】:

我会这样做:

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

Date#>> 的优势在于它会自动为您处理某些事情:

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

【讨论】:

    【解决方案2】:

    当月:

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

    下个月:

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

    【讨论】:

      【解决方案3】:

      从 Ruby 2 开始,“next_month”是一个日期方法:

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

      【讨论】:

        【解决方案4】:
        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
        

        【讨论】:

          【解决方案5】:

          使用http://strfti.me/ 来处理这类事情

          strftime "%Y%m"
          

          【讨论】:

          • 但是下个月怎么弄?
          • 好吧,你必须先给 strftime 提供一个时间。喜欢Time.now.strftime "%Y%m"
          • 我知道。但是下个月我怎么得到呢?
          • 如果你愿意,你可以把它放在一个循环中,并在几个月内迭代,但我不完全确定你在做什么。
          【解决方案6】:

          Ruby 2 Plus 和 rails 4 plus。

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-06-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-05-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多