0

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

  • Can you share the `Check()` method and clarify a little more about your expected behavior? I dont understand what you are trying to do in `setDateAndTime()` - you are calling `Check()` and also have a `Timer` with timeInterval=0 also calling `Check()` – dmorrow Mar 06 '17 at 21:32
  • You can try the approach described [here (SO: how to set seconds to zero for NSDate)](http://stackoverflow.com/questions/1525825/how-to-set-seconds-to-zero-for-nsdate). – FreeNickname Mar 06 '17 at 21:47
  • @dmorrow i added in the check function –  Mar 07 '17 at 00:39
  • @FreeNickname that answers looks like what i want but i need it in swift –  Mar 07 '17 at 00:41

1 Answers1

1

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.

dmorrow
  • 5,152
  • 5
  • 20
  • 31