如何使用任何月份和周数swift 3来获取周开始日期和结束日期?

时间:2017-06-29 07:09:14

标签: ios swift nsdate

我必须实现图表,这样我才能获得周开始日期和周末日期,如果我将传递日期对象和周数。

我怎样才能达到目的,但我没有完全接受?

以下是我的代码: -

平日: -

//Day of week
func getDayOfWeek(today:String)->Int? {
    let formatter  = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    if let todayDate = formatter.date(from: today) {
        let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
        let myComponents = myCalendar.components(.weekday, from: todayDate)
        let weekDay = myComponents.weekday
        return weekDay
    } else {
        return nil
    }
}. 

extension Date {
  var millisecondsSince1970:Int {
      return Int((self.timeIntervalSince1970 * 1000.0).rounded())
  }

  init(milliseconds:Int) {
      self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
  }

  func startOfWeek(weekday: Int?) -> Date {
      var cal = Calendar.current
      var component = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
      component.to12am()
      cal.firstWeekday = weekday ?? 1
      return cal.date(from: component)!
  }

  func endOfWeek(weekday: Int) -> Date {
      let cal = Calendar.current
      var component = DateComponents()
      component.weekOfYear = 1
      component.day = -1
      component.to12pm()
      return cal.date(byAdding: component, to: startOfWeek(weekday: weekday))!
   }
}

  internal extension DateComponents {
    mutating func to12am() {
      self.hour = 0
      self.minute = 0
      self.second = 0
  }

  mutating func to12pm(){
      self.hour = 23
      self.minute = 59
      self.second = 59
  }
}

2 个答案:

答案 0 :(得分:5)

返回给定周数和日期的开始日期和结束日期

func dayRangeOf(weekOfYear: Int, for date: Date) -> Range<Date>
{
    let calendar = Calendar.current
    let year = calendar.component(.yearForWeekOfYear, from: date)
    let startComponents = DateComponents(weekOfYear: weekOfYear, yearForWeekOfYear: year)
    let startDate = calendar.date(from: startComponents)!
    let endComponents = DateComponents(day:7, second: -1)
    let endDate = calendar.date(byAdding: endComponents, to: startDate)!
    return startDate..<endDate
}

print(dayRangeOf(weekOfYear: 12, for: Date()))

考虑print以UTC显示日期,开始日期取决于当前区域设置的first weekday设置。

修改

确定某一周某一周范围的版本

func dayRangeOf(weekOfMonth: Int, year: Int, month: Int) -> Range<Date>? {
    let calendar = Calendar.current
    guard let startOfMonth = calendar.date(from: DateComponents(year:year, month:month)) else { return nil }
    var startDate = Date()
    if weekOfMonth == 1 {
        var interval = TimeInterval()
        guard calendar.dateInterval(of: .weekOfMonth, start: &startDate, interval: &interval, for: startOfMonth) else { return nil }
    } else {
        let nextComponents = DateComponents(year: year, month: month, weekOfMonth: weekOfMonth)
        guard let weekStartDate = calendar.nextDate(after: startOfMonth, matching: nextComponents, matchingPolicy: .nextTime) else {
            return nil
        }
        startDate = weekStartDate
    }
    let endComponents = DateComponents(day:7, second: -1)
    let endDate = calendar.date(byAdding: endComponents, to: startDate)!
    return startDate..<endDate
}

print(dayRangeOf(weekOfMonth: 5, year: 2017, month: 6))

第二个版本的结果类型是可选的,因为有一些计算可能会失败,例如,如果特定月份的周数超出范围。

答案 1 :(得分:0)

对于任何对此感兴趣的人,看起来像OP混淆了weekOfMonth和weekOfYear ......

//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

let cal = Calendar.current


let dateComponents = DateComponents(year: 2018, month: 3, day: 15)
let date = cal.date(from: dateComponents)!

func weekOfMonthStart(forDate date: Date) -> Date {
    var compsToWeekOfMonth = cal.dateComponents([.year, .month, .weekOfYear], from: date)
    compsToWeekOfMonth.day = cal.range(of: .day, in: .weekOfMonth, for: date)?.lowerBound
    return cal.date(from: compsToWeekOfMonth)!
}

有人提到答案会失败,所以包括测试;)

for i in 0...5000 {
    let newDate = cal.date(byAdding: DateComponents(day:i), to: date)!
    weekOfMonthStart(forDate: newDate)
}