user3344977
user3344977

Reputation: 3604

Creating an NSDate and setting AM or PM

I have been trying to figure this out for the past 4 hours and can't seem to figure out how to solve this. A user comes in the app and selects a date on the calendar. The selected date is simply an NSDate. The user can then choose a time that consists of hours, minutes, and seconds and then they can select AM or PM.

So let's say the user chooses a time of 6:57 PM. I need to modify the original NSDate that was created when they selected a date on the calendar, and change it's time data to match the 6:57 PM time that the user just set.

I have been using the dateBySettingHour function of the NSCalendar class and it works great. The only problem is I cannot modify the AM/PM value. All I can do is pass it the hours, minutes, and seconds. Here's the code:

calendar.dateBySettingHour(hours, minute: minutes, second: seconds, ofDate: selectedDate, options: NSCalendarOptions())

I have been playing around with NSDateFormatter, NSDateComponents, and NSCalendar and been going through examples on here but I just can't seem to wrap my head around this and figure it out.

What would be the easiest and most efficient way for me to create a final date in ISO 8601 date format that has the correct month, day, and year info as the original NSDate, but that now also has the correct time information including the AM/PM setting that the user has chosen?

I understand that this is impossible trying to use the dateBySettingHour, but I'm open to trying anything at this point.

Upvotes: 2

Views: 1282

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236305

Xcode 8.3.2 • Swift 3.1

let date = Date()
let hour = 6
let minute = 57
let second = 0
let pm = true

let hours24 = hour == 12 &&  pm ?   12 :
              hour == 12 && !pm ?    0 :
                            !pm ? hour : hour + 12

let dateWithHour = Calendar.current.date(bySettingHour: hours24, minute: minute, second: second, of: date)   // Jun 4, 2017, 6:57 PM"

Upvotes: 4

DCGolf
DCGolf

Reputation: 11

Can you pass in "hours + 12" for PM?

Upvotes: 1

Related Questions