创建单个weekOfYear NSDate对象

时间:2015-06-30 03:51:44

标签: nsdate nsdatecomponents gregorian-calendar

我正在用这个函数创建NSDate对象

-(NSDate *)createDate:(int)Year :(int)WeekOfYear{
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:Year];
    [components setWeekOfYear:WeekOfYear];
    NSDate *date = [_calendar dateFromComponents:components];
    return date;
}

当我循环插入2015,然后是第1周到第52周。 它只用这个

创建52个NSDate对象
2014-12-31 13:00:00 +0000

如何制作它以便有效地创造一年中每周的开始?

1 个答案:

答案 0 :(得分:0)

这对你来说可能为时已晚,但也许对其他人有用。

所以,你不能这样做因为weekOfYear是从完全构造的NSDateComponents计算的,它是从完全构造的NSDate创建的。 你能做的就是这样:

func getFirstDaysOfWeekInYear(year: Int) -> [NSDate] {
  var arrayOfFirstDayOfWeek : [NSDate] = []
  let calendar = NSCalendar.currentCalendar()
  let firstDayOfYearComponents = NSDateComponents()
  firstDayOfYearComponents.day = 1
  firstDayOfYearComponents.month = 1
  firstDayOfYearComponents.year = year
  let firstDayOfYearDate = calendar.dateFromComponents(firstDayOfYearComponents)!

  // if the first day of the year is not a monday, this will give you the first day of
  // the last week of the previous year, it's up to you if you want to remove it or not
  let firstWeekOfYearDate = self.roundWeekDayToFirstWeekDay(firstDayOfYearDate)

  arrayOfFirstDayOfWeek.append(firstWeekOfYearDate)
  for i in 1 ... 52 {
    let componentsToAdd = NSDateComponents()
    componentsToAdd.weekOfYear = i
    arrayOfFirstDayOfWeek.append(calendar.dateByAddingComponents(componentsToAdd, toDate: firstWeekOfYearDate, options: [])!)
  }
  return arrayOfFirstDayOfWeek
}

func roundWeekDayToFirstWeekDay(date: NSDate) -> NSDate {
  let calendar = NSCalendar.currentCalendar()
  let dateComponents : NSDateComponents = calendar
    .components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day],
      fromDate: date)
  let keyDateComponents = NSDateComponents()
  let dayOfWeek = Int(date.stringFromDate(format: "e"))!
  let differenceToMonday = (dayOfWeek == 1 ? 6 : dayOfWeek - 2)
  keyDateComponents.day = dateComponents.day - differenceToMonday
  keyDateComponents.month = dateComponents.month
  keyDateComponents.year = dateComponents.year
  return calendar.dateFromComponents(keyDateComponents)!
}