1

I want to convert Time string to NSDate Time into HH:mm: a format. I have a code right now

let defaultStartTime = json!["start_schedule_datetime"] as? String
 let defaultEndTime = json!["end_schedule_datetime"] as? String



                    print(defaultStartTime,defaultEndTime)

                    dispatch_async(dispatch_get_main_queue(), {

                        let dtf = NSDateFormatter()
                        dtf.timeZone = NSTimeZone(name: "UTC")
                        dtf.dateFormat = "HH:mm a"

                        let defaultStartdate : NSDate = dtf.dateFromString(defaultStartTime!)!
                        let defaultEnddate : NSDate = dtf.dateFromString(defaultEndTime!)!

                        print(defaultStartdate,defaultEnddate)

                        self.startTime.date = defaultStartdate
                        self.endTime.date = defaultEnddate
                        self.endTime.reloadInputViews()
                        self.startTime.reloadInputViews()

                        })

Where:-

start_schedule_datetime = 2016-05-27 13:35:00
end_schedule_datetime = 2016-05-27 19:35:00

Here i want time into HH:mm a. But when i am trying to do that i am getting

fatal error: unexpectedly found nil while unwrapping an Optional value

Can any one please help me here. Thank you

Pushpendra
  • 1,492
  • 1
  • 17
  • 33
  • 1
    You'r date format should be similar to start_schedule_datetime. If you just want to store the date time then store it's converted. Later you can convert it to HH:mm a format for display – Ankita Shah May 27 '16 at 11:52
  • @Bhavin Yes i am sure my default defaultStartTime or defaultEndTime is not null – Pushpendra May 27 '16 at 11:56
  • @Ankita Shah you are right i did convert it but do you have any idea how convert string to NSDate – Pushpendra May 27 '16 at 11:59

2 Answers2

3

Here one of the best solution for everyone. You can easily get what you want from the date. And also you can learn about dateformatter.

Reference 1: http://nsdateformatter.com/

EDIT 1

Reference 2: For Ready made code

Good luck.

Chetan Prajapati
  • 2,249
  • 19
  • 24
0

Check Below Answer. Both Current date and Date picker date is displaying.

 let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
    print(dateFormatter.stringFromDate(NSDate())) //if you want current date
    print(dateFormatter.stringFromDate(yourdatepickername.date) //if you want your selective date
PREMKUMAR
  • 8,283
  • 8
  • 28
  • 51
Himali Shah
  • 181
  • 1
  • 8