I have a UIDatePicker
with the mode time. The date picker lets you pick an hour and minute. I need it to remember the hour and minute not the seconds.
When the app is running the date picker will take the hours and minute the user selected and add the seconds from the time you took to the remembered time.
An example when I select 2:00 pm from the UIDatePIcker this is what I get:
2017-03-07 02:00:36 +0000
However i want to either set the seconds to 00 or remove them like this:
2017-03-07 02:00 +0000
2017-03-07 02:00:00 +0000
Here is my code:
@IBOutlet var datePicker: UIDatePicker!
@IBAction func datePickerchanged(_ sender: Any) {
setDateAndTime()
Check()
let clockString: String = formatADate()
if str == clockString{
takePhoto = true
}
}
func setDateAndTime() {
timercount = Timer.scheduledTimer(timeInterval: 0, target: self, selector: #selector(Check), userInfo: nil, repeats: true)
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm"
_ = formatter.string(from: datePicker.date)
str = dateFormatter.string(from: (datePicker?.date)!)
RunLoop.main.add(timercount, forMode: RunLoopMode.commonModes)
print("setdate ran")
Check()
}
func formatADate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.dateFormat = "hh:mm"
let date = NSDate()
let output = dateFormatter.string(from: date as Date)
print(output)
return output
}
func Check(){
let nowdate = NSDate()
let date2 = datePicker?.date
let elapsed = date2?.timeIntervalSince(nowdate as Date)
print(str)
print(Date())
print(datePicker.date)
if Int(elapsed!) == 0{
takePhoto = true
}
Please help
To modify Date
, I prefer to use https://github.com/MatthewYork/DateTools.
let dateWithZeroSeconds = Date(year:datePicker.date.year, month:datePicker.date.month, day:datePicker.date.day, hour:datePicker.date.hour, minute:datePicker.date.minute, second:0)
You could also do a similar transform with DateComponents
, but DateTools
is a very nice wrapper around all of that.