告诉我这是否是正确的解释。
现在,你会得到这样的结果:
<table>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
...
<th>31</th>
<tr>
<table>
而你想要这样的东西:
<table>
<tr>
<th>26</th> <-- December dates: 26 through end of month
<th>27</th>
<th>28</th>
<th>29</th>
<th>30</th>
<th>31</th>
<th>1</th> <-- January dates: 1 through 25
<th>2</th>
<th>3</th>
<th>4</th>
...
<th>26</th>
<tr>
<table>
如果这是正确的,我建议实际构建一个日期数组:
[2020-12-26, 2020-12-27, 2020-12-28, 2020-12-29, ... 2020-01-01, 2020-01-02, 2020-01-03, 2020-01-04, ... 2020-01-25]
这样我们就不必担心闰年、跨年等问题。Ruby 会为我们处理这些。
所以,我们想要:
- 确定今天的日期是在当月 25 日之前还是之后。
- 如果今天的日期
- 如果今天的日期 > 25,则将本月的第 26 天拉到月底 && 下个月的第 1 天到 25 天
- 将日期放入我们可以在视图中使用的数组中:
(我假设 @project_site.attendance_month 是一个完整的日期对象,而不仅仅是一个月)
class ProjectSite
attr_accessor :attendance_month
# ...
def attendance_date_array
if attendance_month.day <= 25
first_month = attendance_month.beginning_of_month - 1.day
start_day = Date.new(first_month.year, first_month.month, 26)
end_day = Date.new(attendance_month.year, attendance_month.month, 25)
else
start_day = Date.new(attendance_month.year, attendance_month.month, 26)
second_month = attendance_month.end_of_month + 1.day
end_day = Date.new(second_month.year, second_month.month, 25)
end
ary = []
(start_day..end_day).each do |d|
ary << d
end
ary
end
end
此函数将返回如下内容:
[Mon, 26 Oct 2020, Tue, 27 Oct 2020, Wed, 28 Oct 2020, Thu, 29 Oct 2020, Fri, 30 Oct 2020, Sat, 31 Oct 2020, Sun, 01 Nov 2020, Mon, 02 Nov 2020, Tue, 03 Nov 2020, Wed, 04 Nov 2020, Thu, 05 Nov 2020, Fri, 06 Nov 2020, Sat, 07 Nov 2020, Sun, 08 Nov 2020, Mon, 09 Nov 2020, Tue, 10 Nov 2020, Wed, 11 Nov 2020, Thu, 12 Nov 2020, Fri, 13 Nov 2020, Sat, 14 Nov 2020, Sun, 15 Nov 2020, Mon, 16 Nov 2020, Tue, 17 Nov 2020, Wed, 18 Nov 2020, Thu, 19 Nov 2020, Fri, 20 Nov 2020, Sat, 21 Nov 2020, Sun, 22 Nov 2020, Mon, 23 Nov 2020, Tue, 24 Nov 2020, Wed, 25 Nov 2020]
您可以在视图中迭代:
<% @project_site.attendance_date_array.each do |date| %>
<th class="text-center"><%= date.day %></th>
<% end %>