Search code examples
swift3nsdate

NSDate for current date is different?


I was trying to get the next date when I noticed something interesting to me. When I do

let date = NSDate()
let calender = NSCalendar.current
let components = calender.dateComponents([.year, .month, .day], from: date as Date)
    dateLabel.text = "\(components.month!)/\(components.day!)/\(components.year!)"

I get thedate I want, which is the current date.

However, when I do

@IBAction func nextDate(_ sender: UIButton) {

    var oneDayfromNow: NSDate {
        return NSCalendar.current.date(byAdding: .day, value: 1, to: NSDate() as Date)! as NSDate
    }
    print("Current Date: \(calender)")
    print(oneDayfromNow)
}

on my print with the current date I actually get the next date's date and my oneDayfromNow variable is the date 2 days from now. So in short, my current date for my two blocks are different.

Can someone explain to me why is that?

THanks


Solution

  • Here is a quote from apple developer website about NSDate,

    NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).

    So, it means that it does not dictate time in any particular region, rather it is an opaque object which denotes some particular time. It is rather the responsibility of NSDateFormatter to format date and represent it to the timezone that you want it in.