week number of the year, kinda
Preferably in ruby, but the logic would be good enough...
I need the week number of the year given that the week is non-standard. So, say you define a week as Sa开发者_如何学JAVAturday -> Friday. Then, given a date, which week number (1-52) is it?
strftime has %U:
> Time.now.strftime('%U')
> => "28"
...but that of course assumes a standard Sunday -> Saturday week.
Use %W
instead of %U
, it uses Monday as the first day of the week.
Time.now.strftime('%W')
class Date
def sweek
date = self + 1
date.cweek
end
end
# Today is Sunday, 17 July
Date.today.cweek
#=> 28
Date.today.sweek
#=> 29
Maybe can do like this;
def week_dates( week_num )
year = Time.now.year
week_start = Date.commercial( year, week_num, 1 )
week_end = Date.commercial( year, week_num, 7 )
week_start.strftime( "%m/%d/%y" ) + ' - ' + week_end.strftime(
"%m/%d/%y" )
end
We can figure out how to shift the week number from what's returned by %U
(Sun starts the week) by considering this calendar fragment:
August 2015
Su Mo Tu We Th Fr Sa
1 %U => 30
2 3 4 5 6 7 8 %U => 31
9 10 11 12 13 14 15 %U => 32
Let's way we want a Wed-Tue week, abbreviated as format %?
(so we don't have to type out "Wed starts week").
We want:
August 2015
We Th Fr Sa Su Mo Tu
1 2 3 4 %? => 30
5 6 7 8 9 10 11 %? => 31
12 13 14 15 %? => 32
Notice how We-Sa stay in the same week number in both systems, while all other days of the week are moved to the previous week in %?
.
So we can do this:
startd = Date.new(2015, 8, 1)
# show whole month
pp (startd .. (startd >> 1)-1).map {|d|
origw = d.strftime('%U').to_i
# Adjust our new week number if not We-Sa:
neww = ([3, 4, 5, 6].include?(d.wday) ? origw : origw-1)
[d.to_s, origw, neww]
}
If you wanted Sat-Fri week, you can subtract 1 for days that aren't Saturday:
d.wday == 6 ? origw : origw-1
Note that there are a couple edge cases, depending on what you choose your week to be (handling these is left as an exercise for the reader). For our Wed-Tue week:
- Year 2014 starts with Wed, but our algorithm puts Jan 1 in week 0 but it should be week 1 (
%U
puts Jan 1 in week 1 if it's Sunday). - Year 2007 (and other years that start on Mon or Tue) will cause the days before the first Wed to be in week -1 but they should be week 0.
The more days of the week you're adjusting, the more edge cases you'll have. Sat-Fri week will probably have the most problems because you're adjusting 6 out of 7 days.
If you want a ISO week number use %V according strftime documentation
Example:
require 'date'
puts DateTime.parse('2018-12-30 23:59:59').strftime('%G-%V')
puts DateTime.parse('2018-12-31 00:00:00').strftime('%G-%V')
Result:
2018-52
2019-01
Note that it was used %G for year and not %Y.
精彩评论