ios:提前3周(按日期)

时间:2016-02-16 11:49:45

标签: ios swift date nsdate nscalendar

我需要在当前日期之前提前3周。并将所有日期添加到数组。 我怎么能得到这个?

 let date = NSDate()
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
        let comps = calendar?.components([.Day, .WeekOfMonth, .Month], fromDate: date)
        let days = calendar?.rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: date)
        print(days?.length)

这段代码给了我当月的日子。但未来可能需要3个弱点

  

例如今天是16.02我需要打印这样的东西

     

16 17 18 19 20 21 22 23 24 25 26 27 28 29 01 02 04 ....

感谢提前

3 个答案:

答案 0 :(得分:1)

如何生成按要求生成的天数数组

    var date = NSDate()
    var days : [String] = []

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd"

    for _ in 0...20
    {
        days.append(dateFormatter.stringFromDate(date))

        // move on to the next day
        date = NSCalendar.currentCalendar().dateByAddingUnit(
            .Day,
            value: 1,
            toDate: date,
            options: NSCalendarOptions(rawValue: 0))!
    }
    print(days)

答案 1 :(得分:0)

好的,找到了一些解决方案。据我所知,每周7天* 3 = 21

   // MARK: - Next 3 weeks
    func nextThreeWeeks() -> Array<String> {
        let date = NSDate()
        var days : Array<String> = []
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
        dateFormatter.dateFormat = "dd"
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)

        for i in 0 ..< 21 {
            let next21Days = calendar!.dateByAddingUnit(NSCalendarUnit.Day, value: i, toDate: date, options: [])
            days.append(dateFormatter.stringFromDate(next21Days!))
        }
        return days
    }

它将打印以下日期:

  

可选(2016-02-16 12:03:41 +0000)
  可选(2016-02-17 12:03:41 +0000)
  可选(2016-02-18 12:03:41 +0000)
  可选(2016-02-19 12:03:41 +0000)
  ...
  可选(2016-03-06 12:03:41 +0000)
  可选(2016-03-07 12:03:41 +0000)

答案 2 :(得分:0)

我得到的印刷结果的解决方案正是你要求的。

代码和输出

  var arrayDate = [String]()

  override func viewDidLoad()
  {
    super.viewDidLoad()
    for var intWeek = 0; intWeek < 21; ++intWeek
    {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "dd"
        let dateComponents: NSDateComponents = NSDateComponents()
        dateComponents.day = intWeek
        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.dateByAddingComponents(dateComponents, toDate: date, options:NSCalendarOptions(rawValue: 0))
        let startOfDay = formatter.stringFromDate(components!)
        arrayDate.append(startOfDay)
        print("The dates are - \(arrayDate)")
    }
  }   

输出结果

The dates are - ["16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "01", "02", "03", "04", "05", "06", "07"]

非常感谢Anton