0
0

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.

datetimeを使って、本日の注文件数を表示したい。

0
Last updated at Posted at 2020-12-23

まずは「$ rails c」でdatetimeの動きを見てみる。

irb
# 現在時間の取得
[1] pry(main)> dt=DateTime.now
=> Wed, 23 Dec 2020 05:34:58 +0000

# parseで日付情報だけに加工
[2] pry(main)> today=Date.parse(dt.strftime("%Y/%m/%d %H:%M:%S"))
=> Wed, 23 Dec 2020


# ある日付を定義
[3] pry(main)> dt2 = DateTime.new(2020,12,23,5,6,7)     
=> Wed, 23 Dec 2020 05:06:07 +0000

# parseで日付情報だけに加工
[4] pry(main)> the_day=Date.parse(dt2.strftime("%Y/%m/%d %H:%M:%S"))
=> Wed, 23 Dec 2020

# today == the_day
[5] pry(main)> the_day == today
=> true


本日の注文を表示させたい時

状況設定
 ECサイトの管理者top画面で本日の注文件数を表示させたい。
 注文に関するモデル:Order

orders_controller

    def top

        dt=DateTime.now  #まずは、今日の日付を取得。こんな感じ(=> Wed, 23 Dec 2020 05:34:58 +0000)
        today=Date.parse(dt.strftime("%Y/%m/%d %H:%M:%S"))  #日付だけ取り出す
        
        
        orders=Order.all  #とりあえず、注文情報全て引っ張ってくる。
        
        @sum=0  #合計件数用。 ※別に初期化しているわけではないことに注意
                #@sum = @sum + 1 とした時 「@sumって何?」というエラーが出る。

        orders.each do |x|   #理系ですので、xと定義させていただきます。
            dt2=x.created_at
            the_day=Date.parse(dt2.strftime("%Y/%m/%d %H:%M:%S"))
            
            if today == the_day
                @sum = @sum + 1
            end
            
        end
        
    end
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?