参考:https://www.jianshu.com/p/2d3195f9556e
/**
时间Date、日历calender
*/
import UIKit
class LYBCalenderAndDateExtention: NSObject {
}
extension String{
// 获取当前系统时间,转换成字符串
static func dateTodateStr(date:Date)->(String){
let timeFormatter = DateFormatter()
// let timeZone = TimeZone.init(identifier: "UTC")//时区,不加上这个时区设置就是世界标准协调时间,比中国现在的时间少8小时
// timeFormatter.timeZone = timeZone
timeFormatter.locale = Locale.init(identifier: "zh_CN")//本地化设置
timeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"//年月日时分秒毫秒
let nowTimestr = timeFormatter.string(from: date as Date) as String
return nowTimestr
}
//时间字符串转换成date
static func dateStrToDate(dateStr:String)->(Date){
let timeFormatter = DateFormatter()
let timeZone = TimeZone.init(identifier: "UTC")//时区
timeFormatter.timeZone = timeZone//不设置时区,就会少8小时
timeFormatter.locale = Locale.init(identifier: "zh_CN")//本地化设置
timeFormatter.dateFormat = "yyyyMMddHHmmss"
return timeFormatter.date(from: dateStr)!
}
//比较两个日期字符串相差几天
// 调用:String.compareDate(oneDateStr:oneDateStr:String,twoDateStr:String,twoDateStr:"2016-12-24")
static func compareDate(oneDateStr:String,twoDateStr:String)->Int{
let firstDate = oneDateStr
let secondDate = twoDateStr
let cformatter = DateFormatter()
cformatter.dateFormat = "yyyy-MM-dd"
let sDate = cformatter.date(from: firstDate)
let cDate = cformatter.date(from: secondDate)
let intervals = cDate?.timeIntervalSince(sDate!)//时间差(单位是秒)
let day_seconds = 24*3600 //一天的秒数
let days = Int(intervals!)/day_seconds //结果就是两个日期的时间差(单位是天)
return days
}
//MARK: 日历的基本知识
static fileprivate func calendarBasic(){
var calendar = Calendar.current
calendar.locale = Locale.init(identifier: "zh_CN")
print(calendar.timeZone)
print(Date.init())
//Date.init()是默认的值,是格林威治的标准时间,如果需要本地话,可以用formatter格式一下即可
/*
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "yyy-MM-dd HH:mm:ss.S Z" //(格式可按自己需求修整)
let strNowTime = timeFormatter.string(from: Date.init()) as String
print(strNowTime)
*/
/*历标示符
identifier 的范围可以是:
NSCalendarIdentifierGregorian 公历
NSCalendarIdentifierBuddhist 佛教日历
NSCalendarIdentifierChinese 中国农历
NSCalendarIdentifierHebrew 希伯来日历
NSCalendarIdentifierIslamic 伊斯兰日历
NSCalendarIdentifierIslamicCivil 伊斯兰教日历
NSCalendarIdentifierJapanese 日本日历
NSCalendarIdentifierRepublicOfChina 中华民国日历(台湾)
NSCalendarIdentifierPersian 波斯历
NSCalendarIdentifierIndian 印度日历
NSCalendarIdentifierISO8601 ISO8601
*/
// 获取地区信息标示符
let calendarIdentifier = calendar.identifier
print(calendarIdentifier)//gregorian代表公历
// 获取地区信息
let calendarLocalIdentifier = calendar.locale?.identifier
print(calendarLocalIdentifier ?? "calendarLocalIdentifier is nil")
// 获取时区信息
let calendarTimeZone = calendar.timeZone
print(calendarTimeZone)
//获取每周的第一天从星期几开始
let firstWeekDay = calendar.firstWeekday
print(firstWeekDay)//1代表sunday,周日
// 获取第一周必须包含的最少天数
let minDaysInFirstWeek = calendar.minimumDaysInFirstWeek
print(minDaysInFirstWeek)
}
/**
自定义日历转化为date
*/
static func calenderToDate(){
//1, 可以手动创建components,然后进行自定义赋值,还可以将components转换成date对象
var components = DateComponents.init()
components.day = 35
components.month = 5
components.year = 2004
components.weekday = 4
components.hour = 30
let weekday = components.weekday
print(weekday ?? "weekday is nil")
//这里默认的是0时区
let gregorian = Calendar.init(identifier: .gregorian)//公历日历
let customDate = gregorian.date(from: components)
print(customDate ?? "customeDate is nil")
//只需要用DateFormatter格式化一下就可以成为我们当前的8时区
let formatter = DateFormatter.init()
formatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
let theDate = formatter.string(from: customDate!)
print(theDate)
}
/**
date转化为日历
*/
static func dateToCalender(){
//2, 也可将日期转化成dateComponents
let nowTime = Date.init()
let calendar = Calendar.current
let component = calendar.component(.second, from: nowTime)
print(component)
let componentsSet = Set<Calendar.Component>([.year, .month, .day, .hour, .minute, .second])
let componentss = calendar.dateComponents(componentsSet, from: nowTime)
print(componentss)
}
/**
农历和阳历切换
*/
fileprivate func calendarSwitch(){
let date = Date.init()
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
let formatedDate = dateFormatter.string(from: date)
print(formatedDate)
//切换到中国农历(如果之前有创建其他日历,需要先把之前到日历给释放或者清空)
let chinese = Calendar.init(identifier: .chinese)
let components = Set<Calendar.Component>([.year, .month, .day, .hour, .minute, .second])
let theComponents = chinese.dateComponents(components, from: date)
print("阴历的日期是:\(theComponents)")
}
/**
日期当前日期加上一些时间
*/
static func addCertainTime()->String{
let todayTime = Date.init()
let calendar = Calendar.current
var offSetComponents = DateComponents.init()
offSetComponents.hour = 2
let adjustTime = calendar.date(byAdding: offSetComponents, to: todayTime)
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
let theAdjustTime = dateFormatter.string(from: adjustTime!)
return theAdjustTime
}
/**
获取当前周中的星期几
*/
fileprivate func getSundayFromCurrentWeek(){
let todayTime = Date.init()
let calendar = Calendar.current
let weekDayComponents = calendar.dateComponents(Set<Calendar.Component>([.weekday]), from: todayTime)
var componentsToSubtract = DateComponents.init()
componentsToSubtract.day = 0 - (weekDayComponents.weekday! - 1)
let beginningOfWeek = calendar.date(byAdding: componentsToSubtract, to: todayTime)
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
let theBeginningOfWeek = dateFormatter.string(from: beginningOfWeek!)
print(theBeginningOfWeek)
}
/**
计算出一周中的第一天,或周末第一天,或一月中第一天,一年中第一天等
*/
fileprivate func getFirstDayFromWeek(){
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
let dateStr = "2017年05月08日 10时03分25秒 +0800"
let date = dateFormatter.date(from: dateStr)
let calendar = Calendar.current
/*得到该日期的开始时间,也就是凌晨零点
let date = calendar.startOfDay(for: todayDate)
print(date)
*/
/*获取周末开始时间
var beginningOfWeekend: Date = Date.init()
var interval: TimeInterval = 0
let ok = calendar.dateIntervalOfWeekend(containing: date!, start: &beginningOfWeekend, interval: &interval)
if ok == true{
let theBeginningOfWeekend = dateFormatter.string(from: beginningOfWeekend)
print("本周日开始日期是:\(theBeginningOfWeekend)")
}else{
print("给值不是周末")
}*/
//获取本周的第一天
var beginningOfWeek: Date = Date.init()
var interval01:TimeInterval = 0
let ok01 = calendar.dateInterval(of: .weekOfMonth, start: &beginningOfWeek, interval: &interval01, for: date!)
if ok01 == true{
let thebeginningOfWeek = dateFormatter.string(from: beginningOfWeek)
print(thebeginningOfWeek)
}else{
print("失败")
}
}
/**
获取两个日期之间的间隔,通过日历计算
*/
fileprivate func calcTheIntervalBetweenTwoDate(){
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
//第一个日期设置成当前日期好了
let firDate = Date.init()
//第二个日期随手设置一个
let secDateStr = "2017年04月05日 10时03分25秒 +0800"
let secDate = dateFormatter.date(from: secDateStr)
let calendar = Calendar.current
let timeInterval = calendar.dateComponents(Set<Calendar.Component>([.year, .month, .day, .hour, .minute, .second]), from: firDate, to: secDate!)
print(timeInterval)
}
/**
获取日历中的年月日时分每秒
调用: print("\(String(describing: weekDayComponents.day))")//获取天
*/
func getCalenderYMDhms()->DateComponents{
let now = Date.init()
let calendar = Calendar.current
let weekDayComponents = calendar.dateComponents(Set<Calendar.Component>([.year, .month, .day, .hour, .minute, .second]), from: now)
return weekDayComponents
}
}