What's the most efficient way get the first day of the current month?

后端 未结 8 1855
心在旅途
心在旅途 2021-02-12 11:55

With ruby I\'m trying to get format a date as such: 2009-10-01

Where I take the current date (2009-10-26) and then change the day to \"01\".

I know of ways to do

相关标签:
8条回答
  • 2021-02-12 12:38
    Time.parse("2009-10-26").strftime("%Y-%m-01")
    
    0 讨论(0)
  • 2021-02-12 12:39

    If you don't mind including ActiveSupport in your application, you can simply do this:

    require 'active_support'
    date = Date.today.beginning_of_month
    
    0 讨论(0)
  • 2021-02-12 12:43
    require 'date'    
    now = Date.today
    Date.new(now.year, now.month, 1)
    
    0 讨论(0)
  • 2021-02-12 12:47

    If you need the date object without ActiveSupport, you can go back to the last day of the last month and sum 1.

    Date.today - Date.today.mday + 1
    
    0 讨论(0)
  • 2021-02-12 12:50

    Most efficient to get start and end date of current month

    @date = DateTime.now   
    @date.beginning_of_month
    @date.end_of_month
    
    0 讨论(0)
  • 2021-02-12 12:51

    This works...

    Not terribly clever :/

    require 'date'
    Date.parse(Date.parse("2009-10-26").to_s[0,8] << "01")
    
    0 讨论(0)
提交回复
热议问题