3

I have this code which gives today's date in this formate M/dd/yy

let dateFormater = NSDateFormatter()
            dateFormater.dateFormat = "M/dd/yy"
            let todayDate = dateFormater.stringFromDate(NSDate())

How can I get the same thing but with next day's date please?

Wain
  • 118,658
  • 15
  • 128
  • 151
Omid
  • 178
  • 3
  • 12

3 Answers3

12

First, you get a NSDate for the day you need, in this example (one day from now is tomorrow):

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

print(oneDayfromNow)

Then you convert it to your format as string (your case M/dd/yy):

if let oneDayfromNow {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "M/dd/yy"
    let str = dateFormatter.string(from: oneDayfromNow)
    print(str)
}
Boris Y.
  • 4,387
  • 2
  • 32
  • 50
thinkswift
  • 528
  • 1
  • 5
  • 15
  • 1
    +1, Just FYI for `Swift 3` you can use this: ```let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let day = calendar.date(byAdding: .day, value: 1, to: NSDate() as Date, options: [])!``` – mamdouh alramadan Apr 24 '17 at 03:53
3

It's a bit complicated, but it's all things that you need to know anyway.

Why it's difficult: You would think that you could just take NSDate (timeIntervalSinceNow:24 * 60 * 60), adding one day to now. But when you turn on daylight savings time, then 11:30pm plus 24 hours is 00:30am two days later. When daylight savings time is turned off, then 00:30am plus 24 hours can be 11:30pm on the same day.

So you need to create an NSCalendar object, convert NSDate () into components, add one day to the components, convert back to an NSDate (all that gives you the same time on the next day, handling all special cases), and then format the result as you did now.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • This answer should be upvoted more - keep in mind that if you set a dateComponent to (for example) 32, the system will convert into advancing to the next day and using hour 8, which is EXTREMELY helpful when doing this sort of operation. – woody121 Sep 16 '17 at 05:57
-2

I finally used this code to fix it : let dateFormater = NSDateFormatter()

dateFormater.dateFormat = "M/dd/yy"
let todayDate = dateFormater.stringFromDate(NSDate().dateByAddingTimeInterval(24 * 60 * 60))
Omid
  • 178
  • 3
  • 12
  • As gnaher729 answered, there are significant problems with this method. –  Mar 30 '16 at 18:40