首页 文章

删除isLeapMonth:false

提问于
浏览
0

以下代码应返回自创建单元格以来的天数,但它也会返回 isLeapMonth: false . 这是为什么?我该如何删除它?

let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.textLabel?.text = itemArray[indexPath.row].title
let startDate = itemArray[indexPath.row].dateCreated
let currentDate = Date()
let components = Set<Calendar.Component>([.day])
let differenceOfDate = Calendar.current.dateComponents(components, from: startDate!, to: currentDate)
cell.detailTextLabel?.text = "\(differenceOfDate)"
return cell

Image

2 回答

  • 0

    这是因为 differenceOfDate 的类型为 DateComponents ,这不会返回一个数字 . 如果您需要获取天数,可以通过 DateComponents 获取 day 属性来获取此数字

    Calendar.current.dateComponents(components, from: startDate!, to: currentDate).day!
    
  • 0

    由于您只需要天数,因此您应该从结果 DateComponents 中仅提取 day 值并根据需要打印该数字 .

    cell.detailTextLabel?.text = "\(differenceOfDate.day!) days"
    

    请注意,在此处使用 ! 是安全的,因为您特别请求了 .day 组件 .

相关问题