Ruby:
現在の日付の取得
方法:
Rubyの標準ライブラリには、日付と時間を扱うためのDateクラスとTimeクラスが含まれています。以下が現在の日付を取得する方法です:
require 'date'
current_date = Date.today
puts current_dateサンプル出力:
2023-04-12日付に時刻を含める場合、RubyのTimeクラスが適しています:
current_time = Time.now
puts current_timeサンプル出力:
2023-04-12 14:33:07 +0200タイムゾーンの管理など、より多くの機能が必要な場合は、ActiveSupportのようなサードパーティ製のgemを使用することが望ましいかもしれません(Railsの一部ですが、単独で使用できます)。
まず、Gemfileにactivesupportを追加し、bundle installを実行します:
gem 'activesupport'そして、タイムゾーンを扱うには:
require 'active_support/time'
Time.zone = 'Eastern Time (US & Canada)' # 希望のタイムゾーンを設定
current_time_with_zone = Time.zone.now
puts current_time_with_zoneサンプル出力:
Wed, 12 Apr 2023 08:33:07 EDT -04:00