0

I have a UITextView that I need to change for the next "String" in my array every day for 2 times(every 12 hours). I have some array here that I need to use with Date and UITextView. How I need to use Calendar? My simple question is "what I need to do?"

@IBOutlet var ThisTextView: UITextView!
var array = ["a","b","c","d"]
var lastDate: Date?
var currentDate = Date()

    override func viewDidLoad() {
        super.viewDidLoad()

        if currentDate == lastDate {
            // we do nothing 
        } else {
            // we change string to the next in array using some function 
                    // or we write this function here
        }
  • Possible duplicate of [Getting the difference between two NSDates in (months/days/hours/minutes/seconds)](https://stackoverflow.com/questions/27182023/getting-the-difference-between-two-nsdates-in-months-days-hours-minutes-seconds) – bemeyer Sep 11 '17 at 20:17

1 Answers1

0

Here is the code I came up with:

// This is YOUR "lastDate", please supply your own value
let mySuppliedDate = Date()

// You should have your own date to compare to and convert it to seconds
let compareDate:Int = Int(mySuppliedDate.timeIntervalSince1970)

// Current date (today's date)
let currentDate: Date = Date()


let dateFormatter: DateFormatter = DateFormatter()
// Customize the dateStyle property to suit your needs (date format)
dateFormatter.dateStyle = .medium

// This will give you the current time in seconds, or what is known as the (UNIX) Epoch time
// We cast it to an Int because it returns a Double
let currentDateInSecs: Int = Int(currentDate.timeIntervalSince1970)

// Formula: seconds * minutes per hour * no. of hrs
let triggerTime = 60 * 60 * 12

if (currentDateInSecs - compareDate) >= triggerTime {
    // 12 hrs or more have passed

    // Update the Label
    ThisTextView.text = dateFormatter.string(from: currentDate)

}

// else less than 12 hrs have passed

// We do nothing

Please note that you have to supply your own value to mySuppliedDate.

I hope this helps!

idelara
  • 1,786
  • 4
  • 24
  • 48
  • Your code is okey, but how I can Update the Label? maybe something like this : var i = 0 func action() { thisTextView.text = array[i] i = (i + 1) % array.count } – Gleb Valev Sep 15 '17 at 13:03