创建单个 weekOfYear NSDate 对象

Posted

技术标签:

【中文标题】创建单个 weekOfYear NSDate 对象【英文标题】:Creating single weekOfYear NSDate object 【发布时间】:2015-06-30 03:51:44 【问题描述】:

我正在用这个函数创建 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】:

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

因此,您不能这样做,因为 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)!

【讨论】:

以上是关于创建单个 weekOfYear NSDate 对象的主要内容,如果未能解决你的问题,请参考以下文章

如何创建代表下一个指定日期时间的完整 NSDate 对象?

如何创建过去的新 NSDate 对象,例如比另一个日期早 1 秒?

iOS NSDate 转换为单个数字

如何使 NSDate 与关联对象一起工作?

OC基础--常用类的初步介绍与简单使用之NSDate

是否可以在单个 NSmanagedObejct 类中使用标量和对象属性?