【问题标题】:Comparing a formatted date with current将格式化日期与当前日期进行比较
【发布时间】:2018-06-07 16:49:41
【问题描述】:

我正在比较一个名为“file.txt”的文件中的日期,以将其作为列表放入 tableView。我在文件中有一个日期作为当前日期作为最后的测试。它读取它,但不将其识别为当前日期。我有一个日期格式化程序,将格式设置为“MM/dd/yyyy”。检查在从手机中提取当前日期之前和之后的日期都可以正常工作。

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
}

}

我关心的文件中的日期格式为“06/07/2018”,我的文件中其余日期的格式也是如此。

更新了输出比较:

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)

应该是忽略格式化后的时间。

【问题讨论】:

  • 打印 currentDatefileDate 并使用应比较为同一日期的两者的输出更新您的问题。
  • @rmaddy 我添加了打印,但仍然显示时间。我不在乎时间,这就是我告诉它格式化为“MM/dd/yyyy”的原因。

标签: swift date-comparison


【解决方案1】:

问题是两个Date 实例上的compare 比较低到微秒。

您的let currentDate = Date() 行为您提供了精确到微秒的“现在”时刻。

当您读取文件并从“MM/dd/yy”字符串创建Date 时,您会得到一个Date,精确到给定日期当地时间午夜的微秒。

所以即使两个日期在同一天,一个是当前时间,一个是当地时间午夜。

解释了为什么它不能正常工作,下面是简单的解决方法。将您的比较代码更新为以下内容:

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
}

【讨论】:

  • currentDate &lt; fileDate!
  • @Sulthan 有趣的是,我们有时会忽略显而易见的事情。谢谢。
  • 没问题,我们已经在 Obj-C 中使用这种模式多年了,所以我猜它来自于 :)
  • @rmaddy 感谢您的帮助,这对我有用。我还发现我实际上并没有格式化当前日期。格式化后,我的代码确实有效。
猜你喜欢
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多