我试图显示最近的日期。我有以下代码:
def closest_birthdate(birthdates)
sorted_dates = birthdates.sort_by do |_, value|
(DateTime.parse(value) - DateTime.now).abs
end
name, birthday = sorted_dates.first
"#{name} has his birthday on #{birthday} "
end
hash = {
'William' => '2017-09-05',
'Henk' => '2017-10-12',
'Richard' => '2017-10-10',
}
closest_birthdate(hash)
输出结果为:
"William has his birthday on 2017-10-5"
如何只显示如下的月份和日期?
"William has his birthday on 10-5"
我试图删除散列中的年份,但我认为如果我这样做,代码就不会再识别日期了。
答案 0 :(得分:5)
试试这个
require 'date'
"#{name} has his birthday on #{Date.parse(birthday).strftime('%m-%d')}"