JaguarJmn
JaguarJmn

Reputation: 7

Comparing a formatted date with current

I am comparing dates from a file called "file.txt" to put into a tableView as a list. I have a date in the file as the current date as a test at the end. It reads it, but doesn't recognize it as the current date. I have a date formatter setting the format to "MM/dd/yyyy". The checks work correctly with dates before and after the current date being pulled from the phone.

import UIKit
import GoogleMaps


class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var banner: UIImageView!
@IBOutlet weak var tableView: UITableView!

var arrayMarkers = [GMSMarker]()
var dictMarkers = [String:String]()

override func viewDidLoad() {
    super.viewDidLoad()

    banner.image = #imageLiteral(resourceName: "Branding_Iron_Banner")



    tableView.estimatedRowHeight = 155.0
    tableView.rowHeight = UITableViewAutomaticDimension



    let formatter = DateFormatter()
    formatter.dateFormat = "MM/dd/yyyy"
    let currentDate = Date()

    print(formatter.string(from: currentDate))


    guard let path = Bundle.main.path(forResource: "file", ofType: "txt") else {
        print("File wasn't found")
        return
    }


    let filemgr = FileManager()
    if filemgr.fileExists(atPath: path) {
        print("Found the file to read from!")

    }

    guard let streamReader = StreamReader(path: path) else {
        print("Dang! StreamReader couldn't be created!")
        return
    }

    var lineCounter = 0
    var lat = 0.0
    var log = 0.0
    var address = ""
    var date = ""
    var time = ""
    var snip = ""
    var snip2 = ""
    var same = true
    while !streamReader.atEof {

        guard let nextLine = streamReader.nextLine() else {
            print("Oops! Reached the end before printing!")
            break
        }

        if(lineCounter % 5 == 0) {
            lat = (nextLine as NSString).doubleValue
        }
        else if(lineCounter % 5 == 1) {
            log = (nextLine as NSString).doubleValue
        }
        else if(lineCounter % 5 == 2) {
            address = nextLine
        }
        else if(lineCounter % 5 == 3) {
            date = nextLine

            let fileDate = formatter.date(from: date)


            if (currentDate.compare(fileDate!) == .orderedSame) {
                snip2 = date
                print("Same dates compare with current: \(String(describing: fileDate))")
                same = true
            }
            if(fileDate?.compare(currentDate) == .orderedDescending) {
                print("Date comes after current: \(String(describing: fileDate))")
                snip2 = date
                same = true
            }
            if(fileDate?.compare(currentDate) == .orderedAscending) {
                same = false
            }


        }
        else if(lineCounter % 5 == 4){

            if(same == true) {

                time = nextLine
                let position = CLLocationCoordinate2DMake(lat, log)
                let marker = GMSMarker(position: position)
                marker.title = address
                snip = snip2 + "\n"+time
                marker.snippet = snip
                arrayMarkers.append(marker)
                print("\n\(String(describing: marker.title))")
                same = false


            }
        }

        lineCounter += 1
        print("\(lineCounter): \(nextLine)")
    }


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


    return arrayMarkers.count
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 2
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 2
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!


    //print("Inside the assigning of table cells")
    let marker = arrayMarkers[indexPath.row]
    //print(marker.snippet!)

    cell.textLabel?.text = marker.title
    cell.detailTextLabel?.text = marker.snippet
    return cell
}

}

The date I care about from my file is formatted as "06/07/2018" as is the format for the rest of my dates in my file.

Updated with output comparison:

74: 05/30/2018
75: 8:00 am to 5:00 pm
76: 41.313000
77: -105.576195
78: 1513 Fraternity Row

The current date is: 2018-06-08 15:32:22 +0000

The file date is: Optional(2018-06-08 06:00:00 +0000)

It is supposed to be ignoring the time after the formatting.

Upvotes: 0

Views: 43

Answers (1)

rmaddy
rmaddy

Reputation: 318814

The issue is that compare on two Date instances compares down to the microsecond.

Your line let currentDate = Date() gives you an exact moment of "now" to the microsecond.

As you read the file and create a Date from the "MM/dd/yy" string, you get a Date to the microsecond of midnight local time on the given date.

So even if the two dates are on the same day, one is the current time and one is midnight local time.

With that explanation of why it isn't working out of the way, here's the simple fix. Update your comparison code to the following:

if Calendar.current.isDate(currentDate, inSameDayAs: fileDate!) {
    snip2 = date
    print("Same dates compare with current: \(String(describing: fileDate))")
    same = true
} else if currentDate < fileDate! {
    print("Date comes after current: \(String(describing: fileDate))")
    snip2 = date
    same = true
} else {
    // Not the same or descending so it must be ascending
    same = false
}

Upvotes: 1

Related Questions