Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

datetime

ruby

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.

like image 722
Shpigford Avatar asked Oct 26 '09 22:10

Shpigford


People also ask

How do I get the first day of my current month?

To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates. Copied! const now = new Date(); const firstDay = new Date(now. getFullYear(), now.


6 Answers

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

require 'active_support'
date = Date.today.beginning_of_month
like image 121
PatrickTulskie Avatar answered Oct 12 '22 15:10

PatrickTulskie


Time.parse("2009-10-26").strftime("%Y-%m-01")
like image 32
Bob Aman Avatar answered Oct 12 '22 14:10

Bob Aman


require 'date'    
now = Date.today
Date.new(now.year, now.month, 1)
like image 35
CodeJoust Avatar answered Oct 12 '22 15:10

CodeJoust


Most efficient to get start and end date of current month

@date = DateTime.now   
@date.beginning_of_month
@date.end_of_month
like image 33
Dinesh Vaitage Avatar answered Oct 12 '22 15:10

Dinesh Vaitage


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
like image 27
Ken Stipek Avatar answered Oct 12 '22 16:10

Ken Stipek


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
like image 41
TorvaldsDB Avatar answered Oct 12 '22 14:10

TorvaldsDB