Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

swift - NSDate of yesterday

How do I create an NSDate object with a custom date other than the current date? For example I would like to create a var of yesterday or of 2 days ago.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use NSCalendar for calculating dates. For example, in Swift 3 the date two days before today is:

let calendar = Calendar.current
let twoDaysAgo = calendar.date(byAdding: .day, value: -2, to: Date())

Or in Swift 2:

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

Or to get the first of the month, you can get the day, month and year from the current date, adjust the day to the first of the month, and then create a new date object. In Swift 3:

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

Or in Swift 2:

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

There are lots of useful functions in the NSCalendar/Calendar class, so you should investigate that further. See the NSCalendar class reference for more information.

But I would advise against doing any manual adjustments of date objects by adjusting it by some time interval that is a multiple of the seconds per day (e.g. 24*60*60). That technique works fine if you're just adding some time interval, but for date calculations, you really want to use calendar object, to avoid problems stemming from daylight savings and the like.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...