NSDate昨天

Mar*_*cus 41 nsdate swift

如何NSDate使用除当前日期之外的自定义日期创建对象?例如,我想创建一个昨天或两天前的变量.

Rob*_*Rob 69

您应该NSCalendar用于计算日期.例如,在Swift 3中,今天前两天的日期是:

let calendar = Calendar.current
let twoDaysAgo = calendar.date(byAdding: .day, value: -2, to: Date())
Run Code Online (Sandbox Code Playgroud)

或者在Swift 2中:

let calendar = NSCalendar.currentCalendar()
let twoDaysAgo = calendar.dateByAddingUnit(.Day, value: -2, toDate: NSDate(), options: [])
Run Code Online (Sandbox Code Playgroud)

或者,要获得本月的第一天,您可以从当前日期获取日期,月份和年份,将日期调整为该月的第一天,然后创建新的日期对象.在Swift 3中:

var components = calendar.dateComponents([.year, .month, .day], from: Date())
components.day = 1
let firstOfMonth = calendar.date(from: components)]
Run Code Online (Sandbox Code Playgroud)

或者在Swift 2中:

let components = calendar.components([.Year, .Month, .Day], fromDate: NSDate())
components.day = 1
let firstOfMonth = calendar.dateFromComponents(components)
Run Code Online (Sandbox Code Playgroud)

NSCalendar/ Calendarclass中有许多有用的函数,因此您应该进一步调查.有关更多信息,请参阅NSCalendar类参考.

但我建议不要对日期对象进行任何手动调整,方法是将其调整为每天秒数的倍数(例如24*60*60).如果您只是添加一些时间间隔,那么该技术可以正常工作,但是对于日期计算,您确实希望使用日历对象,以避免因夏令时等而产生的问题.


Ben*_*Ben 24

这是Swift 4.2-XCode 10的解决方案

let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
Run Code Online (Sandbox Code Playgroud)

因此两天前:

let twoDaysAgo = Calendar.current.date(byAdding: .day, value: -2, to: Date())
Run Code Online (Sandbox Code Playgroud)


mic*_*ion 0

let twoDaysAgo = NSDate(timeIntervalSinceNow: -2*24*60*60)
Run Code Online (Sandbox Code Playgroud)