gpt4 book ai didi

ruby-on-rails - 您如何找到一天在一个月中的星期几?

转载 作者:数据小太阳 更新时间:2023-10-29 07:08:53 24 4
gpt4 key购买 nike

我似乎无法理解这个可能很简单的问题..

假设我有日期..

Fri, 14 Sep 2012 18:37:50 +0200

我如何找出这个月的这个日期是星期几?是第一个,第二个..?第三个?

谢谢!

最佳答案

为什么要使用图书馆? Ruby 默认有它:

Week number:
The week 1 of YYYY starts with a Sunday or Monday (according to %U
or %W). The days in the year before the first week are in week 0.
%U - Week number of the year. The week starts with Sunday. (00..53)
%W - Week number of the year. The week starts with Monday. (00..53)

> Time.zone.parse("2012-01-01").strftime("%U")
=> "01"

因此,鉴于我们可以找到给定日期在一年中的第几周,我们可以做一些数学运算来计算出它发生在一个月中的第几周。

> week_of_year_for_first_of_month = Time.zone.parse("2012-07-01").strftime("%U").to_i
> week_of_target_date = Time.zone.parse("2012-07-14").strftime("%U").to_i
> week_occurs_in = week_of_target_date - week_of_year_for_first_of_month + 1
> week_occurs_in # => 2

或者一个方法:

def week_of_month_for_date(date)
my_date = Time.zone.parse(date)
week_of_target_date = my_date.strftime("%U").to_i
week_of_beginning_of_month = my_date.beginning_of_month.strftime("%U").to_i
week_of_target_date - week_of_beginning_of_month + 1
end

> week_of_month_for_date("2012-07-14") # => 2
> week_of_month_for_date("2012-07-15") # => 3

关于ruby-on-rails - 您如何找到一天在一个月中的星期几?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12428638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com