获得年度第一周NSCalendar

时间:2015-09-22 15:37:18

标签: date swift2 nscalendar

我试图将一周开头的日期放在应用中。 然而,在2017年,这导致了不期望的行为,因为今年有一周“1”2次,

从1月1日星期日开始,到12月31日星期日。 我的程序找到后者。给我结果 '01 -01-2018'应该是'02 -01-2017'

如何确保我的程序找到第一个可用日期?

这是我的代码:

getFirstDay(Int(weekNummer)!, year: yearWrap)

func getFirstDay(weekNumber:Int, year:Int)->String?{
    let Calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let dayComponent = NSDateComponents()
    dayComponent.weekOfYear = weekNumber
    dayComponent.weekday = 2
    dayComponent.year = year
    var date = Calendar.dateFromComponents(dayComponent)
    if ((weekNumber == 1 || weekNumber == 52 || weekNumber == 53) && Calendar.components(.Month, fromDate: date!).month != 1 ){
        dayComponent.year = year - 1
        date = Calendar.dateFromComponents(dayComponent)
    }
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    return String(dateFormatter.stringFromDate(date!))
}

1 个答案:

答案 0 :(得分:1)

NSCalendar完成日期数学

func firstDayOfWeek(week: Int, inYear year : Int) -> NSString {
  let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
  let components = NSDateComponents()
  components.weekOfYear = week
  components.yearForWeekOfYear = year
  components.weekday = 2 // First weekday of the week (Sunday = 1)
  let dateFormatter = NSDateFormatter()
  dateFormatter.dateFormat = "dd-MM-yyyy"
  let date = calendar.dateFromComponents(components)!
  return dateFormatter.stringFromDate(date)
}

firstDayOfWeek(1, inYear : 2017) // 02-01-2017
firstDayOfWeek(1, inYear : 2018) // 01-01.2018