How to get Int from DateFormatter() in Swift3

我只是一个虾纸丫 提交于 2020-01-07 06:47:18

问题


I want to remove some data from my UITableView when the data is passed over 24 hours. I saved date as String. I want to check the date but because it is String, how am I able to turn that data into Int value in order to check how many hours have passed since the data is last entered? Is there any good code for that to happen? This date data is stored in Firebase.

 let currentDateTime = Date()
 let formatter = DateFormatter()
 formatter.timeStyle = .medium
 formatter.dateStyle = .long
 let date = formatter.string(from: currentDateTime)

回答1:


You need:

  1. Your date
  2. Add 24 hours to that date
  3. Compare that new date with "now"

I am assuming you have some date already:

let myDate: Date = ...

Let's add 24 hours:

let endDate: Date = Calendar.current.date(byAdding: .hour, value: 24, to: myDate, wrappingComponents: true)!

Did 24 hours already passed since my date?

let now = Date()
let expired = (endDate < now)

I am not sure why would you even use a date formatter for this task.




回答2:


Try this:

 let currentDateTime = Date()
 let formatter = DateFormatter()
 formatter.dateFormat = "hh"
 let date = formatter.string(from: currentDateTime)
 print(date)// Time in string
 print(Int(date)!) // Time in Int


来源:https://stackoverflow.com/questions/41933710/how-to-get-int-from-dateformatter-in-swift3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!