0

I want to apply the current date as title to a button once it is tapped by the user. I already have the button read "USED" once clicked, but I want it to include the date too. For example, the button is clicked on January 1st 2018, how would I get it to read "USED 01/01/18"? And on the contrary, if it was used the second of january it would need to read "USED 01/02/18" My code for the toggle button is included below, my particular button only toggles once.

var didClick: Bool = false

@IBAction func special1BTNpressed(_ sender: UIButton) {
    if !didClick {
        didClick = true
        sender.setTitle("USED", for: .normal)
    }
}
Teetz
  • 3,475
  • 3
  • 21
  • 34
  • This sounds like you want to store this date when your app gets terminated? You can see how to get the current date here: https://stackoverflow.com/questions/24070450/how-to-get-the-current-time-as-datetime – Teetz Aug 06 '18 at 17:58
  • what if i don't want the hour and only want the date ex. mm/dd/yyyy @Teetz – Jim Halpert Aug 06 '18 at 22:32

2 Answers2

3

Combining your question and zulutime's answer you could use the following:

import UIKit

class MyViewController: UIViewController {

    var didClick: Bool = false

    @IBAction func special1BTNpressed(_ sender: UIButton) {

        if !didClick {
            didClick = true

            let date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "MM/dd/yyyy"
            let result = formatter.string(from: date)

            sender.setTitle("USED " + result, for: .normal)
        }
    }
}
Teetz
  • 3,475
  • 3
  • 21
  • 34
  • @JimHalpert Glad i could help. If it's working i would appreciate it if you accept my answer. – Teetz Aug 07 '18 at 18:18
0

You can use a DateFormatter to get the current date and format it

import Foundation

class MyViewController: UIViewController {
    var didClick: Bool = false
    @IBAction func special1BTNpressed(_ sender: UIButton) {
        if !didClick {
            didClick = true

            let date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "MM/dd/yyyy"
            let result = formatter.string(from: date)

            sender.setTitle("USED " + result, for: .normal)
        }
    }
}
zulutime
  • 101
  • 4