Reputation:
I'm trying to show the closest date. I have the following code:
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)
The output is:
"William has his birthday on 2017-10-5"
How can I display only the month and day like the following?
"William has his birthday on 10-5"
I tried to delete the years in the hash, but I think the code doesn't recognize dates anymore if I do that.
Upvotes: 0
Views: 72
Reputation: 30056
Try this one
require 'date'
"#{name} has his birthday on #{Date.parse(birthday).strftime('%m-%d')}"
Upvotes: 5