Search code examples
swiftnsdateformatter

NSDateFormatter subtracting a day when removing time


I am trying to remove time from date using NSDateFormatter. This is the code:

func dateWithOutTime( datDate: NSDate?) -> NSDate {

    let formatter = NSDateFormatter()
    formatter.dateFormat = "dd-MM-yyyy"
    let stringDate: String = formatter.stringFromDate(datDate!)
    let dateFromString = formatter.dateFromString(stringDate)

return dateFromString!
}

If i send in ex 04-01-2016 12:00:00, the return is 03-01-2016 23:00:00 I have tried changing the dateFormat, but it still keeps to subtracting a day from the date... Why? Please Help :)


Solution

  • The easiest way is to use startOfDayForDate of NSCalendar

    Swift 2:

    func dateWithOutTime( datDate: NSDate) -> NSDate {
        return NSCalendar.currentCalendar().startOfDayForDate(datDate)
    }
    

    Swift 3+:

    func dateWithOutTime(datDate: Date) -> Date {
        return Calendar.current.startOfDay(for: datDate)
    }
    

    or to adjust the time zone to UTC/GMT

    Swift 2:

    func dateWithOutTime( datDate: NSDate) -> NSDate {
      let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
      calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
      return calendar.startOfDayForDate(datDate)
    }
    

    Swift 3+:

    func dateWithOutTime(datDate: Date) -> Date {
      var calendar = Calendar(identifier: .gregorian)
      calendar.timeZone = TimeZone(secondsFromGMT: 0)!
      return calendar.startOfDay(for: datDate)
    }