使用NSDate在Swift中无法正确获取日期

时间:2016-10-04 06:01:18

标签: ios swift nsdate

我想打印日期[1,2,3 ....当前日期],但没有得到正确的结果。 因为当我在代码中设置第一天是“1”时,输出在[2,3,4]中。当我设定日为“0”时。结果显示正确但显示额外日期[1,2,3,4,5]。今天是2016年10月4日,作为我的时区。

    let date = NSDate()
    let components = NSCalendar.currentCalendar().components([.Day , .Month , .Year], fromDate: date)
    let year =  components.year
    let month = components.month
    let day =  1  // Output is [2,3,4]
 // let day =  0   than o/p [1,2,3,4,5]


    dateFormatatter.dateFormat = "MMMM yyyy"
    monthNameLabel.text = dateFormatatter.stringFromDate(date)

    startDate.year = year
    startDate.month = month
    startDate.day = day
    let startDateNSDate = calendar.dateFromComponents(startDate)!

    var dateStart = startDateNSDate // first date
    let endDate = NSDate() // last date

    dateFormatatter.dateFormat = "dd"


    while dateStart.compare(endDate) != .OrderedDescending {
        // print(fmt.stringFromDate(date))
        // Advance by one day:
        dateStart = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateStart, options: [])!


        let dateFormat1 = NSDateFormatter()
        dateFormat1.dateFormat = "dd-MM-yyyy"

        dateArrayCalendar.addObject(dateFormatatter.stringFromDate(dateStart))
        dateArrayForCompare.addObject(dateFormat1.stringFromDate(dateStart))

    }

我想要这样的结果[1,2,3,4]

同样的问题

let componentsForCompare = calendar.components([.Year, .Month], fromDate: date)
        let startOfMonth = calendar.dateFromComponents(componentsForCompare)!
        print(startOfMonth)//2016-09-30 18:30:00 +0000
        print(dateFormatatter.stringFromDate(startOfMonth)) //01

它提供不同的输出

1 个答案:

答案 0 :(得分:0)

您需要在while循环的结尾处增加日期,而不是在开头:

while dateStart.compare(endDate) != .OrderedDescending {
    // print(fmt.stringFromDate(date))
    // Advance by one day:

    let dateFormat1 = NSDateFormatter()
    dateFormat1.dateFormat = "dd-MM-yyyy"

    dateArrayCalendar.addObject(dateFormatatter.stringFromDate(dateStart))
    dateArrayForCompare.addObject(dateFormat1.stringFromDate(dateStart))

    dateStart = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateStart, options: [])!
}