「Swift」Date获取过去一段时间日期方法

421 阅读1分钟
前言:

有时候需要获取过去某段的时间日期,如昨天、前7天、前一个月的日期等,这时候需要使用自定义方法来获取相对应的日期

自定义方法:

/// 输入要过去日期的时间,返回相应日期字符串
static func getLastDate(lastTimeInterval: TimeInterval) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let lastTime: TimeInterval = lastTimeInterval // 往前减去往前时间的时间戳
        let lastDate = Date().addingTimeInterval(lastTime)
        let lastDay = dateFormatter.string(from: lastDate)
        return lastDay
    }

方法使用:

以昨天、前7天、前一个月进行举例说明

let yesterdayTime = Date.getLastDate(lastTimeInterval: -(24*60*60))
let lastSevenTime = Date.getLastDate(lastTimeInterval: -(7*24*60*60))
let lastMonthTime = Date.getLastDate(lastTimeInterval: -(30*24*60*60))

整理不易,望大家多多点赞收藏!感谢大家!