2

A simple code, for converting string date to NSDate. But don't know why it return actual date - 1

var start_date: NSDate?
var end_date: NSDate?

let dateformatter = NSDateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd"

start_date = dateformatter.dateFromString("2016-09-01")!
end_date = dateformatter.dateFromString("2016-09-07")!

print(start_date)
print(end_date)

output

2016-08-31 18:30:00 +0000
2016-09-06 18:30:00 +0000
Manish Jain
  • 842
  • 1
  • 11
  • 29

2 Answers2

1

You need to set timezone in your dateformat to UTC

    let dateformatter = NSDateFormatter()
    dateformatter.dateFormat = "yyyy-MM-dd"
    dateformatter.timeZone = NSTimeZone(name: "UTC")

    start_date = dateformatter.dateFromString("2016-09-01")!
    end_date = dateformatter.dateFromString("2016-09-07")!

This has resolve my issue.

Crazy Developer
  • 3,464
  • 3
  • 28
  • 62
  • I found your and Sweeper both's answer are useful and give me now correct output. So what is the default TimeZone swift assign for NSDateFormatter(). – Manish Jain Aug 23 '16 at 08:54
  • I think it's your local time zone @ManishJain – Sweeper Aug 23 '16 at 08:58
  • 1
    This will produce new problems. NSDate are stored in UTC, while the nsdateformatter take current timezone into account. with this code you will alter the dates to be 5:30 hours off. – vikingosegundo Aug 23 '16 at 09:00
0

I experienced similar problems before. I think it's related to your time zone. And after some trying, I did this and it worked somehow...

let components = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: yourDate)
components.timeZone = NSTimeZone(name: "GMT")
let correctDate = NSCalendar.currentCalendar().dateFromComponents(components)!

Basically, switch the time zone to GMT...

I recommend you to create an extension:

extension NSDate {
    func switchToCorrectTimeZone() -> NSDate {
        let components = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: self)
        components.timeZone = NSTimeZone(name: "GMT")
        return NSCalendar.currentCalendar().dateFromComponents(components)!
    }
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313