Search This Blog

Showing posts with label Date. Show all posts
Showing posts with label Date. Show all posts

Wednesday, November 23, 2016

How to find nearest(closest) date to today

If we have array of dates and we need to find what date is neasrest to today date. There is special method in iOS SDK API - timeIntervalSince
public func timeIntervalSince(_ date: Date) -> TimeInterval

This method will return double value - time interval between two dates - self date object and parameter date. Also this time interval can be positive or negative. So for getting nearest date we need to get absolute positive value of time interval. For that purpose we will use method fabs
public func fabs(_: Double) -> Double

Algorithm - How to define nearest date to today
func findNearestDateToToday(datesArray: [Date]) -> Date {
        let today = Date()
        let firstDate = datesArray[0]
        var min = fabs(today.timeIntervalSince(firstDate))
        var minIndex = 0
        for i in 1..<datesArray.count {
            let currentDate = datesArray[i]
            let currentMin = fabs(today.timeIntervalSince(currentDate))
            if currentMin < min {
                min = currentMin
                minIndex = i
            }
        }
        return datesArray[minIndex]
}

Monday, October 10, 2016

iOS Swift. How to show Date in local Time Zone

For showing date in local time zone we need to use DateFormatter class and set to it our local time zone:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
        
let localTZ = TimeZone.current
dateFormatter.timeZone = localTZ
print(localTZ.abbreviation())
        
self.userLastTimeRefreshedLabel.text = String("\(dateFormatter.string(from: date))")