14
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsのDateまたはDateTimeを用いてカレンダーを実装

Last updated at Posted at 2016-03-15

Date(Time)オブジェクトを利用してカレンダーを実装

command
$ bundle exec rails console

まずはrails consoleを起動してDateオブジェクトの挙動を調べます。 *この記事を書いているのは2016年3月15日です

```commans:command $today = Date.today => Tue, 15 Mar 2016

$today.month
=> 3

$today.day
=> 15

$today.year
=> 2016

$today.beginning_of_month.wday
=> 2 #月初めの日の曜日を取得。ハッシュなのでsundayが0

$today.strftime("< %m / %Y >")
=> < 03 / 2016 >

<p>
まだ他にも多くのメゾットがありますが本題に入ろうと思います
</p>
<h2>
railsで簡易カレンダーの実装
</h2>

```ruby:calendar_controller.rb
class CalendarController < ApplicationController

  def index
    @today = Date.today
    from_date = Date.new(@today.year, @today.month, @today.beginning_of_month.day).beginning_of_week(:sunday)
    to_date = Date.new(@today.year, @today.month, @today.end_of_month.day).end_of_week(:sunday)
    @calendar_data = from_date.upto(to_date)
  end

end
index.html.erb
<table>
  <tr>
    <% t('date.abbr_day_names').each do |day_name| %>
      <td>
        <%= day_name %>
      </td>
    <% end %>
  </tr>
  <% @calendar_data.each do |date| %>
    <% if date.wday == 0 %>
      <tr>
    <% end %>
    <td>
      <%= date.day %>
    </td>
    <% if date.wday == 6 %>
    </tr>
    <% end %>
  <% end %>
</table>
<p><%= @today.strftime("< %m / %Y >") %></p>

ja.yml
ja:
  date:
    abbr_day_names:
      - Sun
      - Mon
      - Tue
      - Wed
      - Thu
      - Fri
      - Sat

これでtableに展開されるカレンダーができましたd( ̄  ̄)

14
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?