业务上需要计算两个日期相差几天,来显示上一次操作时间过去多久。官方为我们提供了NSCalendar类,来管理时间。
天的参数是:NSCalendar.Unit.day
如果计算相差的小时数,可改为NSCalendar.Unit.hour; day改为hour。
// MARK: - 计算两日期间相差的天数
/**计算两日期间相差的天数*/
class func distancesFrom(_ startingDate: Date, to resultDate: Date) -> Int {
let gregorian = Calendar(identifier: Calendar.Identifier.gregorian)
//如果计算相差的小时数,可改为.CalendarUnitHour; day改为hour
let comps = (gregorian as NSCalendar).components(NSCalendar.Unit.day, from: startingDate, to: resultDate, options:.wrapComponents)
return comps.day!
}
整个时间管理类
/**时间日期管理器*/
class HTDateManager {
// MARK: - 日期格式转字符串
class func switchToNSDateFrom(_ dateString: String, dateFormat: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = dateFormat
return formatter.date(from: dateString)
}
// MARK: - 日期转字符串格式
/**日期转字符串格式*/
class func switchToStringFrom(_ date: Date, dateFormat: String) -> String? {
let formatter = DateFormatter()
formatter.dateFormat = dateFormat
return formatter.string(from: date)
}
// MARK: - 计算两日期间相差的天数
/**计算两日期间相差的天数*/
class func distancesFrom(_ startingDate: Date, to resultDate: Date) -> Int {
let gregorian = Calendar(identifier: Calendar.Identifier.gregorian)
//如果计算相差的小时数,可改为.CalendarUnitHour; day改为hour
let comps = (gregorian as NSCalendar).components(NSCalendar.Unit.day, from: startingDate, to: resultDate, options:.wrapComponents)
return comps.day!
}
// MARK: - 获取本地时区与世界零时区的时差
/**获取本地时区与世界零时区的时差*/
class func distanceIntervalForLocalTimeZon() -> Int {
return TimeZone.autoupdatingCurrent.secondsFromGMT(for: Date())
}
// MARK: - 指定日期,所在的“day”单元,在“month”中有多少个(即指定日期所在月有多少天)
/**
指定日期,所在的“day”单元,在“month”中有多少个(即指定日期所在月有多少天)
*/
class func numberOfDaysInMonthDepandOn(_ date: Date) -> Int {
return (Calendar.current as NSCalendar).range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: date).length
}
// MARK: - 指定日期,所在“month“单元里,该单元的第一个日期(即目标日期所在月的第一天)
/**
指定日期,所在“month“单元里,该单元的第一个日期(即目标日期所在月的第一天)
*/
class func fetchFirstDayInMonthDepandOn(_ date: Date) -> Date? {
var startDate: Date?
var interval: TimeInterval = 0
startDate = Date()
Calendar.current.dateInterval(of: .month, start: &startDate!, interval: &interval, for: date)
return startDate as Date?
}
// MARK: - 指定日期为当周的周几(1为周日)
/**
指定日期为当周的周几(1为周日)
*/
class func dayIndexInWeeklyDepandOn(_ date: Date) -> Int {
// 把目标日期转为yyy-MM-dd字符串
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateString = dateFormatter.string(from: date)
// 取出对应的 年、月、日
var dateArr: [String] = dateString.components(separatedBy: "-")
// 设置NSDateComponts
var dateComponts = DateComponents()
dateComponts.setValue(Int(truncating: NumberFormatter().number(from: dateArr[0])!), for: .year)
dateComponts.setValue(Int(truncating: NumberFormatter().number(from: dateArr[1])!), for: .month)
dateComponts.setValue(Int(truncating: NumberFormatter().number(from: dateArr[2])!), for: .day)
let targetDate = Calendar.current.date(from: dateComponts)!
let weekdayIndex = (Calendar.current as NSCalendar).component(NSCalendar.Unit.weekday, from: targetDate)
return weekdayIndex
}
// MARK: - 指定日期为周几
class func getDayNameBy(stringDate: String) -> String
{
let df = DateFormatter()
df.dateFormat = "YYYY-MM-dd"
let date = df.date(from: stringDate)!
df.dateFormat = "EEEE"
return df.string(from: date);
}
// MARK: - 指定日期所在月一共有多少个周
/**
指定日期所在月一共有多少个周
*/
class func numberOfWeeksInMonthDepandOn(_ date: Date) -> Int {
// 指定日期当月第一天为周几(周日为1)
let firstDayIndex = dayIndexInWeeklyDepandOn(fetchFirstDayInMonthDepandOn(date)!)
// 指定日期所在月有多少天
let daysInMonth = numberOfDaysInMonthDepandOn(date)
var weeks: Int = 0
// 第一周有多少天
let firstWeekSurplusDays: Int = 7 - firstDayIndex + 1
weeks += (daysInMonth - firstWeekSurplusDays) / 7 + 1
weeks += (daysInMonth - firstWeekSurplusDays) % 7 == 0 ? 0 : 1
return weeks
}
// MARK: - 指定日期在所在月为第几周
/**
指定日期在所在月为第几周(第一周为0)
*/
class func weekIndexInMonthDepandOn(_ date: Date) -> Int {
// 指定日期当月第一天为周几(周日为1)
let firstDayIndex = dayIndexInWeeklyDepandOn(fetchFirstDayInMonthDepandOn(date)!)
// 第一周拥有的天数
let daysInFirstWeek = 7 - firstDayIndex + 1
// 指定日期为当月的几号
let dateString = LWDateManager.switchToStringFrom(date, dateFormat: "yyyy-MM-dd")
let dateComposes = dateString?.components(separatedBy: "-")
let days = NumberFormatter().number(from: dateComposes!.last!)!.intValue
var weeks: Int = 0
if days <= daysInFirstWeek {
weeks += 0
} else {
weeks += (days - daysInFirstWeek) / 7
if (days - daysInFirstWeek) % 7 > 0 {
weeks += 1
}
}
return weeks
}
/**
* 返回day天后的日期(若day为负数,则为|day|天前的日期)
*/
class func dateGenerateNewDate(_ date:NSDate,_ day:NSInteger) -> NSDate {
let calendar = NSCalendar.current
let componentsToAdd = NSDateComponents()
componentsToAdd.day = day
let dateAfterDay = calendar.date(byAdding: componentsToAdd as DateComponents, to: date as Date, wrappingComponents: false)
return dateAfterDay! as NSDate
}
//返回当前天的字符串
class func currentDayString()->String{
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd"
let date = Date()
return dateformatter.string(from: date)
}
//返回月份的英文简写
class func monthString(_ Index: Int)->String{
switch Index {
case 1: return "Jan"
case 2: return "Feb"
case 3: return "Mar"
case 4: return "Apr"
case 5: return "May"
case 6: return "Jun"
case 7: return "Jul"
case 8: return "Aug"
case 9: return "Sep"
case 10: return "Oct"
case 11: return "Nov"
case 12: return "Dec"
default:return ""
}
}
}