使用 Swift 中的周数获取一周的第一天

get first day of week using Weeknumber in Swift

我正在尝试获取本周的第一天(比如本周,我应该获取 2015-09-13)。

但是我在 Apple 提供的源代码中找不到合适的函数。

代码应该是这样的...

print(getFirstDay(40)) // Should print 27

func getFirstDay(weekNumber:Int)->Int?{
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    if let todayDate = formatter.dateFromString(weekNumber) {
        let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let myComponents = myCalendar.dateFromComponents(.weekOfYear)
        let date = myComponents.date
        return date
    } else {
        return nil
    }
}

但是上面的代码不起作用(很明显),但我认为应该朝着正确的方向发展。

我怎样才能做到这一点?

/* 不重要 */ 我正在尝试在 table 视图中创建一个日历应用程序,该视图由 4 周的部分分隔,我想知道新的一周从哪一天开始。

    func getFirstDay(weekNumber:Int)->String?{
        let Calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let dayComponent = NSDateComponents()
        dayComponent.weekOfYear = weekNumber
        dayComponent.weekday = 1
        dayComponent.year = 2015
        var date = Calendar.dateFromComponents(dayComponent)

        if(weekNumber == 1 && Calendar.components(.Month, fromDate: date!).month != 1){
            print(Calendar.components(.Month, fromDate: date!).month)
            dayComponent.year = 2014
            date = Calendar.dateFromComponents(dayComponent)
        }
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy"
        return String(dateFormatter.stringFromDate(date!))
    }

到目前为止我所做的代码非常粗糙。

它适用于查找一周的第一天 ;)!

let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitYear | .CalendarUnitWeekOfYear | .CalendarUnitWeekday, fromDate: NSDate())

components.calendar = calendar

components.weekday = 2 // 2 = Monday
components.weekOfYear = 39

let firstDayOfWeek = components.date

这会给出当年第 39 周星期一的日期。

经过反复试验,如果您使用的是 Swift3 + iOS10,这是正确的解决方案。这会计算 Dec/Jan 跨越边界的正确日期。

extension Date {
    var components:DateComponents {
        let cal = NSCalendar.current
        return cal.dateComponents(Set([.year, .month, .day, .hour,.minute, .second, .weekday, .weekOfYear, .yearForWeekOfYear]),from: self)
    }
}

private static func getWeekFirstDay(from sourceDate:Date) -> Date? {
let Calendar = NSCalendar(calendarIdentifier: .gregorian)!
    var sourceComp = sourceDate.components
    var comp = DateComponents()
    comp.weekOfYear = sourceComp.weekOfYear
    comp.weekday = 1
    comp.yearForWeekOfYear = sourceComp.yearForWeekOfYear
    return Calendar.date(from: comp)
}

Swift 4.2

更通用的解决方案

func getFirstDay(WeekNumber weekNumber:Int, CurrentYear currentYear: Int)->String?{
    let Calendar = NSCalendar(calendarIdentifier: .gregorian)!
    var dayComponent = DateComponents()
    dayComponent.weekOfYear = weekNumber
    dayComponent.weekday = 1
    dayComponent.year = currentYear
    var date = Calendar.date(from: dayComponent)
    
    if(weekNumber == 1 && Calendar.components(.month, from: date!).month != 1){
        //print(Calendar.components(.month, from: date!).month)
        dayComponent.year = currentYear - 1
        date = Calendar.date(from: dayComponent)
    }
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy/MM/dd"
    return String(dateFormatter.string(from: date!))
}

我的解决方案 Xcode 12 和 Swift 5

extension Date {

   var year: Int? {
       var calendar = Calendar.current
       let currentComponents = calendar.dateComponents([.year], from: self)
       return currentComponents.year
   }
} 

class func getWeekOfYear(from week: Int, year: Int? = Date().year, locale: Locale? = nil) -> Date? {
        var calendar = Calendar.current
        calendar.locale = locale
        let dateComponents = DateComponents(calendar: calendar, year: year, weekday: 1, weekOfYear: week)
        return calendar.date(from: dateComponents)
    }

你可以运行它:

  getWeekOfYear(from: 38)             // Optional(2020-09-13 22:00:00 +0000)
  getWeekOfYear(from: 38, year: 2020) // Optional(2020-09-13 22:00:00 +0000)
  getWeekOfYear(from: 38, year: 2020, locale: Locale(identifier: de_DE) ) // Optional(2020-09-13 22:00:00 +0000)

插件:

extension Date {

   func isBetween(_ date1: Date, and date2: Date) -> Bool {
      return (min(date1, date2) ... max(date1, date2)).contains(self)
   }

   var startOfWeek: Date? {
      var calendar = Calendar.current
      return calendar.dateInterval(of: .weekOfMonth, for: self)?.start
   }

   var endOfWeek: Date? {
       var calendar = Calendar.current
       return calendar.dateInterval(of: .weekOfMonth, for: self)?.end
   }

   var startOfMonth: Date? {
       var calendar = Calendar.current
       return calendar.dateInterval(of: .month, for: self)?.start
   }

   var endOfMonth: Date? {
       var calendar = Calendar.current
       return calendar.dateInterval(of: .month, for: self)?.end
   }

   var weekNumber: Int? {
       var calendar = Calendar.current
       let currentComponents = calendar.dateComponents([.weekOfYear], from: self)
       return currentComponents.weekOfYear
   }

   var monthNumber: Int? {
       var calendar = Calendar.current
       let currentComponents = calendar.dateComponents([.month], from: self)
       return currentComponents.month
   }
} 

你可以运行它:

let date = Date() // Optional(2020-09-13 22:00:00 +0000)
date.monthNumber  // Optional(9)
date.weekNumber   // Optional(38)

...