将时间转换为上午 12 点之后的昨天



我想将时间转换为上午 12 点之后的昨天。例如:如果消息在晚上 11:35 发送,现在的时间是凌晨 12:00,我会将其转换为昨天

let dateformatter = DateFormatter()
dateformatter.timeZone = NSTimeZone.local
dateformatter.dateFormat = "MM/dd/yyyy"
let interval = Calendar.current.dateComponents([.year, .month, .day], from: self, to: Date())
if let day = interval.day, day > 0 {
   return day == 1 ? "Yesterday at" + " " + formatter.string(from: date as Date) : dateformatter.string(from: date as Date) 
}

此代码从发送时间转换为昨天 24 小时后。

日历中有一个名为isDateInYesterday的方法

extension Date {
    func isYesterday() -> Bool {
        let calendar = Calendar.current     
        return calendar.isDateInYesterday(self)
    }
}

相关内容

最新更新