Viju
Viju

Reputation: 427

How we find out a next day in Swift

How do we find out a next day in Swift language? Suppose today is 2014-09-15. How we can find out a date: 2014-09-16.

Upvotes: 1

Views: 1576

Answers (3)

Grimxn
Grimxn

Reputation: 22487

Calendar has a built in function which allows us to avoid using DateComponent directly:

let nextDay: Date = Calendar.current.date(byAdding: .day, value: 1, to: date)

as commentator https://stackoverflow.com/users/3165426/develobär points out, you must use Calendar and not assume the length of any particular day, as not all days are the same length (Daylight savings time transitions, leap seconds, etc.)

Upvotes: 0

Anthony Kong
Anthony Kong

Reputation: 40664

Swift code without using NSCalendar:

var today = NSDate()
var res = today.dateByAddingTimeInterval(24*60*60)
println("\(today), \(res)") // 2014-09-15 10:31:28 +0000, 2014-09-16 10:31:28 +0000

Upvotes: 2

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Use NSDateComponents:

var calendar:NSCalendar = NSCalendar.currentCalendar()      
var dayFutureComponents:NSDateComponents = NSDateComponents()

 dayFutureComponents.day = 1 // aka 1 day

 let today = NSDate.date()  // Sep 15, 2014, 1:10 PM
 var oneDay:NSDate = calendar.dateByAddingComponents(
         dayFutureComponents, toDate: today!, options: nil)!

Output:

"Sep 16, 2014, 1:10 PM"

Upvotes: 6

Related Questions