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 3 years have passed since last update.

【Ruby初学者】日付/曜日をたった4行で出す方法

Posted at

##某スクールのRuby問題を解いた備忘録。

test.rb
now = Time.new
puts "現在は西暦#{now.year}#{now.month}#{now.day}日"
week = ["日","月","火","水","木","金","土"]
puts week[now.wday] + '曜日です' 

と、記述しLinuxで実行すると

test.rb
% ruby test.rb
現在は西暦2021128
木曜日です

となる。

ちなみに、railsのアプリケーションで表示するときには、
コントーラーファイルで、インスタンス変数を定義して、

controller.rb
def index
   wd = ["日", "月", "火", "水", "木", "金", "土"]
   time = Time.now
   @date = time.strftime("%Y/%m/%d(#{wd[time.wday]})")
   ampm = time.hour < 12 ? "AM" : "PM"
   @time =time.strftime("#{ampm} %I:%M")
end

ビューファイルに、コードを埋め込む。

view.rb
  <div class = "date"><%= @date %></div>
  <div class = "time"><%= @time %></div>

ブラウザで表示されるのは、こんな感じ。

Qiita

##参考記事

[Ruby入門] 14. 日付と時刻を扱う(全パターン網羅)/@prgseekさま
https://qiita.com/prgseek/items/c0fc2ffc8e1736348486

0
0
1

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?