Skip to content

Instantly share code, notes, and snippets.

@gouf
Created August 13, 2020 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gouf/b6a7a12e42afab3fd63ce4ed34030fc6 to your computer and use it in GitHub Desktop.
Save gouf/b6a7a12e42afab3fd63ce4ed34030fc6 to your computer and use it in GitHub Desktop.
○ヶ月○日と表示させる - https://teratail.com/questions/284238#reply-403944
require 'active_support'
require 'active_support/core_ext'
#
# 関数の定義
#
def date_duration(base_date, after_date)
duration_parts =
ActiveSupport::Duration.build(after_date.to_i - base_date.to_i).parts
# 起点日も 1日としてカウントする (+1)
duration_in_days = (after_date - base_date).to_i + 1
years, months, days, weeks =
duration_parts[:years], duration_parts[:months], duration_parts[:days], duration_parts[:weeks]
# * n週 に吸収された値を還元 (n weeks * 7 days)
# * 起点日も 1日としてカウントする (+1)
days += weeks * 7 + 1
case [years, months, days]
in [0, 0, 0] then "今日"
in [0, 0, _] then "#{days}日後"
in [0, _, 0] then "#{months}ヶ月後" + "(#{duration_in_days}日)"
in [0, _, _] then "#{months}ヶ月#{days}日後(#{duration_in_days}日)"
in [_, 0, 0] then "#{years}年後" + "(#{duration_in_days}日)"
in [_, _, 0] then "#{years}年#{months}ヶ月後" + "(#{duration_in_days}日)"
in [_, 0, _] then "#{years}年" + "#{days}日後(#{duration_in_days}日)"
else "#{years}年#{months}ヶ月#{days}日後(#{duration_in_days}日)"
end
end
#
# 巻数に渡すデータの定義と関数の使用
#
date_time_args = [
2020, # year
7, # month
3, # day
0, # hour
0, # min
0, # sec
'+09:00' # time zone
]
base_date = DateTime.new(*date_time_args)
after_date = base_date.advance(years: 0, months: 1, days: 8)
# For debug
format = '%Y/%m/%d'
pp [base_date, after_date].map { |x| x.strftime(format) }
# => ["2020/07/03", "2020/08/11"]
pp date_duration(base_date, after_date)
# => "1ヶ月9日後(40日)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment