Shpigford
Shpigford

Reputation: 25338

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

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 this, but was curious what the shortest way is, code wise, to pull this off.

Upvotes: 23

Views: 26623

Answers (8)

TorvaldsDB
TorvaldsDB

Reputation: 972

Like

Date.today.beginning_of_day
Date.today.end_of_day

And

Date.today.beginning_of_week
Date.today.end_of_week

There also is

Date.today.beginning_of_year
Date.today.end_of_year

Upvotes: 1

Dinesh Vaitage
Dinesh Vaitage

Reputation: 3183

Most efficient to get start and end date of current month

@date = DateTime.now   
@date.beginning_of_month
@date.end_of_month

Upvotes: 4

Ken Stipek
Ken Stipek

Reputation: 1522

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

Upvotes: 2

oklahomabigdog
oklahomabigdog

Reputation: 11

require 'active_support/core_ext'
Date.today.beginning_of_month

Upvotes: 0

PatrickTulskie
PatrickTulskie

Reputation: 961

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

require 'active_support'
date = Date.today.beginning_of_month

Upvotes: 70

CodeJoust
CodeJoust

Reputation: 3790

require 'date'    
now = Date.today
Date.new(now.year, now.month, 1)

Upvotes: 15

SoreGums
SoreGums

Reputation: 53

This works...

Not terribly clever :/

require 'date'
Date.parse(Date.parse("2009-10-26").to_s[0,8] << "01")

Upvotes: 0

Bob Aman
Bob Aman

Reputation: 33239

Time.parse("2009-10-26").strftime("%Y-%m-01")

Upvotes: 26

Related Questions