1

i want to get start and end time from date which i select from datepicker.

here is my code

 func handleDatePicker(sender: UIDatePicker) {
        let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

    let startOfDay = NSCalendar.currentCalendar().startOfDayForDate(sender.date)

    let components = NSDateComponents()
    components.hour   = 23
    components.minute = 59
    components.second = 59
    let endOfDay = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: startOfDay, options: NSCalendarOptions(rawValue: 0))
}

but i am getting output like 2016-10-12 12:00:00

my question is how to get how to get output like this

12-09-2016 00:00:00 AND 12-09-2016 23:59:59
Krutarth Patel
  • 3,407
  • 6
  • 27
  • 54
  • 2
    The format for 24-hour time is `HH`, not `hh`: http://stackoverflow.com/questions/2135267/nsdateformatter-with-24-hour-times, http://stackoverflow.com/questions/25657123/swift-nsdateformatter-not-working. – Martin R Sep 13 '16 at 07:32
  • 1
    Check [this article](http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/). Was very helpful for me – Elena Sep 13 '16 at 07:33
  • 1
    what the output you get here sender – Anbu.Karthik Sep 13 '16 at 08:40
  • 2
    FYI: The end of the day is not 23:59:59. iOS can handle nanoseconds, so there's at least one billion possible `Date`s between 23:59:59 and 00:00:00. The end of the day is therefor defined as the start of the next day. You should calculate the start of the next day (which is well defined) and use `<` comparison. – Matthias Bauch Sep 13 '16 at 12:46

1 Answers1

2

Try Below Code :-

        let calendar = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)
        calendar?.timeZone =  NSTimeZone(abbreviation: "GMT")!
        let startOfDay = calendar?.startOfDayForDate(sender.date)

        print("startDay \(startOfDay)")
        let components = NSDateComponents()
        components.hour   = 23
        components.minute = 59
        components.second = 59
        components.timeZone =  NSTimeZone(abbreviation: "GMT")

        let endOfDay = calendar?.dateByAddingComponents(components, toDate: startOfDay!, options: NSCalendarOptions(rawValue: 0))
        print("end Day \(endOfDay)")
SBK
  • 101
  • 5