This is my original timestamp code How should I modify to cite him How should I modify the code to refer to the "extension Date {" code
func getDatas(){
if let timestamp = document.get("timestamp") as? TimeInterval {
let date = Date(timeIntervalSince1970: timestamp)
let post = Post(email: email, caption: caption, imageUrl: imageURL, date: date)
...
...
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FeedCell
let post = self.postArray[indexPath.row]
let date = post.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm"
let dateString = dateFormatter.string(from: date)
self.getUserInfo(userEmail: postArray[indexPath.row].email,cell: cell)
cell.captionLabel.text = postArray[indexPath.row].caption
cell.postImage.sd_setImage(with: URL(string: postArray[indexPath.row].imageUrl))
cell.timeLabel.text = dateString
I want to change to the following date display method, but the changes have no effect
extension Date {
static func timeString(timeInterval: TimeInterval) -> String{
let date = getNowDateFromatAnDate(Date(timeIntervalSince1970: timeInterval/1000))
let formatter = DateFormatter()
if date.isToday() {
//是今天
formatter.dateFormat = "今天HH:mm"
return formatter.string(from: date)
}else if date.isYesterday(){
//是昨天
formatter.dateFormat = "昨天HH:mm"
return formatter.string(from: date)
}else if date.isSameWeek(){
//是同一周
let week = date.weekdayStringFromDate()
formatter.dateFormat = "\(week)HH:mm"
return formatter.string(from: date)
}else{
formatter.dateFormat = "yyyy-MM-dd HH:mm"
return formatter.string(from: date)
}
}
...
...
...
...
How should I modify to cite him
CodePudding user response:
The static keyword allow us to attach the method to a class/struct rather than to instances of it.
And since the static func timeString(timeInterval: TimeInterval) -> String
in your Date extension returns a string you can replace your Post date: Date
variable with timeString: String
and then you can access it directly:
if let timestamp = document.get("timestamp") as? TimeInterval {
let timeString = Date.timeString(timeInterval: timestamp)
let post = Post(email: email, caption: caption, imageUrl: imageURL, timeString: timeString)
// ...
}
cell.timeLabel.text = post.timeString