从自定义日期swift

时间:2017-03-22 07:03:46

标签: swift

我有一个应用程序,用户可以从中选择日期。如何从所选日期设置明天日期。例如,如果用户选择日期24,则打印25,如果用户选择日期31,则打印1。

现在我正在使用当前日期来设定明天的日期

let dates = Date()
var tomorrow: Date {
    return Calendar.current.date(byAdding: .day, value: 1, to: Date())!
}         

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

let dateOutDefault = dateFormatter.string(from: tomorrow as Date)

如何使用自定义日期执行此类操作?

2 个答案:

答案 0 :(得分:8)

import Foundation

extension Date {

    var tomorrow: Date? {
        return Calendar.current.date(byAdding: .day, value: 1, to: self)
    }
}

let today = Date()

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy, HH:mm b"

if let tomorrow = today.tomorrow {
    let tomorrowString = dateFormatter.string(from: tomorrow)
    print("\(tomorrowString)" // "Mar 23, 2017, 00:14 AM\n"
}

答案 1 :(得分:0)

    let dayComponenet = NSDateComponents()
    dayComponenet.day = 1

    let theCalendar = NSCalendar.currentCalendar()
    let nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: NSCalendarOptions(rawValue: UInt(0)))
    print(nextDate);

    let date = nextDate
    let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
    let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: date!)
    print(components.day);