swift2 计算给定月份中的周数- Swift

llew8vvj  于 2022-11-06  发布在  Swift
关注(0)|答案(5)|浏览(241)

看了一些关于SO的不同建议后,我不能确定为什么下面的函数不起作用。它似乎对一些月份返回6,对另一些月份返回5。当把星期改为日子时,它工作得很好。
例如,尝试

weeksInMonth(8, forYear 2015)

结果6.
我相信我对日历上的“第一个工作日”属性有一个错误的理解,但还没有找到苹果或网上的充分解释。
已尝试了.WeekOfMonth 和.WeekOfYear。同样无法找到确切差异的解释。
任何建议都是非常受欢迎的。

func weeksInMonth(month: Int, forYear year: Int) -> Int?
{
    if (month < 1 || month > 12) { return nil }

    let dateString = String(format: "%4d/%d/01", year, month)
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy/MM/dd"
    if let date = dateFormatter.dateFromString(dateString),
       let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    {
        calendar.firstWeekday = 2 // Monday
        let weekRange = calendar.rangeOfUnit(.WeekOfMonth, inUnit: .Month, forDate: date)
        let weeksCount = weekRange.length
        return weeksCount
    }
    else
    {
        return nil
    }
}

更新日期:

抱歉,我的问题不清楚。我正在计算一个月中有多少周包含星期一。对于八月,应该是5周。

hpxqektj

hpxqektj1#

您的代码计算一个月中出现的周数(完整或部分)。您显然需要的是给定月份中的星期一数。使用NSDateComponents,特别是weekdayOrdinal属性,您可以计算一个月中的第一个(weekdayOrdinal=1)和最后一个(weekdayOrdinal=-1)星期一。然后计算周数差(并加一)。

Swift 2中可能的实现:

func numberOfMondaysInMonth(month: Int, forYear year: Int) -> Int?
{
    let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    calendar.firstWeekday = 2 // 2 == Monday

    // First monday in month:
    let comps = NSDateComponents()
    comps.month = month
    comps.year = year
    comps.weekday = calendar.firstWeekday
    comps.weekdayOrdinal = 1
    guard let first = calendar.dateFromComponents(comps)  else {
        return nil
    }

    // Last monday in month:
    comps.weekdayOrdinal = -1
    guard let last = calendar.dateFromComponents(comps)  else {
        return nil
    }

    // Difference in weeks:
    let weeks = calendar.components(.WeekOfMonth, fromDate: first, toDate: last, options: [])
    return weeks.weekOfMonth + 1
}
func numberOfMondaysInMonth(_ month: Int, forYear year: Int) -> Int? {
    var calendar = Calendar(identifier: .gregorian)
    calendar.firstWeekday = 2 // 2 == Monday

    // First monday in month:
    var comps = DateComponents(year: year, month: month,
                               weekday: calendar.firstWeekday, weekdayOrdinal: 1)
    guard let first = calendar.date(from: comps)  else {
        return nil
    }

    // Last monday in month:
    comps.weekdayOrdinal = -1
    guard let last = calendar.date(from: comps)  else {
        return nil
    }

    // Difference in weeks:
    let weeks = calendar.dateComponents([.weekOfMonth], from: first, to: last)
    return weeks.weekOfMonth! + 1
}
b0zn9rqh

b0zn9rqh2#

其实你的问题是:一个月有多少个星期一?
我的方法是计算一个月的第一个星期一,这可以通过将CalendarUnit WeekdayOrdinal设置为1来完成。然后获得总天数并进行一些计算。
雨燕1.2

func mondaysInMonth(month: Int, forYear year: Int) -> Int?
{
  if 1...12 ~= month {

    let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let components = NSDateComponents()
    components.weekday = 2 // Monday
    components.weekdayOrdinal = 1
    components.month = month
    components.year = year

    if let date = calendar.dateFromComponents(components)  {
      let firstDay = calendar.component(.CalendarUnitDay, fromDate: date)
      let days = calendar.rangeOfUnit(.CalendarUnitDay, inUnit:.CalendarUnitMonth, forDate:date).length
      return (days - firstDay) / 7 + 1
    }
  }
  return nil
}

雨燕2号

func mondaysInMonth(month: Int, forYear year: Int) -> Int?
{
  guard 1...12 ~= month else { return nil }

  let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
  let components = NSDateComponents()
  components.weekday = 2 // Monday
  components.weekdayOrdinal = 1
  components.month = month
  components.year = year

  if let date = calendar.dateFromComponents(components)  {
    let firstDay = calendar.component(.Day, fromDate: date)
    let days = calendar.rangeOfUnit(.Day, inUnit:.Month, forDate:date).length
    return (days - firstDay) / 7 + 1
  }
  return nil
}
gmol1639

gmol16393#

雨燕2

下面的代码计算一个月中的周数。它不依赖于该月的开始或结束日期。

func weeksInMonth(month: Int, year: Int) -> (Int)? {

  let calendar = NSCalendar.currentCalendar()

  let comps = NSDateComponents()
  comps.month = month+1
  comps.year = year
  comps.day = 0

  guard let last = calendar.dateFromComponents(comps) else {
    return nil
  }
  // Note: Could get other options as well
  let tag = calendar.components([.WeekOfMonth,.WeekOfYear,
       .YearForWeekOfYear,.Weekday,.Quarter],fromDate: last)

  return tag.weekOfMonth

}

// Example Usage:

if let numWeeks = weeksInMonth(8,year: 2015) {
  print(numWeeks) // Prints 6
}

if let numWeeks = weeksInMonth(12,year: 2015) {
  print(numWeeks) // Prints 5
}
dddzy1tm

dddzy1tm4#

雨燕4+:

//-- Get number of weeks from calendar
func numberOfWeeksInMonth(_ date: Date) -> Int {
     var calendar = Calendar(identifier: .gregorian)
     calendar.firstWeekday = 1
     let weekRange = calendar.range(of: .weekOfMonth,
                                    in: .month,
                                    for: date)
     return weekRange!.count
}

//-- Implementation
let weekCount = numberOfWeeksInMonth(Date)
jk9hmnmh

jk9hmnmh5#

斯威夫特4+:
根据组件生成日期:

let dateComponents = DateComponents.init(year: 2019, month: 5)
let monthCurrentDayFirst = Calendar.current.date(from: dateComponents)!
let monthNextDayFirst = Calendar.current.date(byAdding: .month, value: 1, to: monthCurrentDayFirst)!
let monthCurrentDayLast = Calendar.current.date(byAdding: .day, value: -1, to: monthNextDayFirst)!

从以下日期检测周数:

let numberOfWeeks = Calendar.current.component(.weekOfMonth, from: monthCurrentDayLast)

相关问题