Array sort by date and month only (ignore year)

ぃ、小莉子 提交于 2020-01-06 05:09:53

问题


I have following festival array:

id = 1, Start_date = 2011-11-01 , End_date = 2016-12-31

[[1, 2011-11-01 , 2016-12-31],
[2, 2011-11-28 , 2016-12-31],
[3, 2011-10-01 , 2015-12-31],
[4, 2011-11-28 , 2021-12-31],
[5, 2010-11-15 , 2016-12-31],
[6, 2011-07-01 , 2017-12-31],
[7, 2012-02-01 , 2013-02-19],
[8, 2011-03-21 , 2015-04-30],
[9, 2012-03-01 , 2016-03-20]]

I need to sort this by start_date start from current date but ignore year here (use only month and day).

Actually these are festival's start dates and end dates. I need to show running festivals first(order by: start_date) then upcoming festivals(order by: start_date separately).

For example:

festival A: start_date: 15-may  - end_date: 15-june  
festival B: start_date: 01-june - end_date: 20-june
festival C: start_date: 01-oct  - end_date: 30-oct
  • If today is 14-june then order should be A B C
  • if today is 16-june then order should be: B C A
  • and finally if today is 1-Feb then order should be: A B C

Thank you in advance for responses.


回答1:


Assuming that start_date and end_date are Date objects:

# get the festivals from the database
festivals = Festival.all

# define the day of interest
day = Date.today

# partition the festivals into running and upcoming
# based on the day of the year (1-366)
running, upcoming = festivals.partition { |f|
  (f.start_date.yday..f.end_date.yday).include? day.yday
}

# sort each array by day of the year
running.sort_by!{ |f| f.start_date.yday }
upcoming.sort_by!{ |f| f.start_date.yday }


来源:https://stackoverflow.com/questions/11326305/array-sort-by-date-and-month-only-ignore-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!