swift 對(duì)日期的處理大全( 類擴(kuò)展 Date+Extension 和 公共類 DateClass)

摘要:類擴(kuò)展Date+Extension
import UIKit 
extension Date{//MARK:-獲取日期各種值//MARK:年
func year() ->Int { 

let calendar = NSCalendar.current 

let com = calendar.dateComponents([.year,.month,.day], from: self) 

return com.year! 

} 

//MARK: 日 

func day() ->Int { 

let calendar = NSCalendar.current 

let com = calendar.dateComponents([.year,.month,.day], from: self) 

return com.day! 

} 

//MARK: 星期幾 

func weekDay()->Int{ 

let interval = Int(self.timeIntervalSince1970) 

let days = Int(interval/86400) // 24*60*60 

let weekday = ((days + 4)%7+7)%7 

return weekday == 0 ? 7 : weekday 

} 

//MARK: 當(dāng)月天數(shù) 

func countOfDaysInMonth() ->Int { 

let calendar = Calendar(identifier:Calendar.Identifier.gregorian) 

let range = (calendar as NSCalendar?)?.range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: self) 

return (range?.length)! 

} 

//MARK: 當(dāng)月第一天是星期幾 

func firstWeekDay() ->Int { 

//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat. 

let calendar = Calendar(identifier:Calendar.Identifier.gregorian) 

let firstWeekDay = (calendar as NSCalendar?)?.ordinality(of: NSCalendar.Unit.weekday, in: NSCalendar.Unit.weekOfMonth, for: self) 

return firstWeekDay! - 1 

} 

//MARK: - 日期的一些比較 

//是否是今天 

func isToday()->Bool { 

let calendar = NSCalendar.current 

let com = calendar.dateComponents([.year,.month,.day], from: self) 

let comNow = calendar.dateComponents([.year,.month,.day], from: Date()) 

return com.year == comNow.year &;&; com.month == comNow.month &;&; com.day == comNow.day 

} 

//是否是這個(gè)月 

func isThisMonth()->Bool { 

let calendar = NSCalendar.current 

let com = calendar.dateComponents([.year,.month,.day], from: self) 

let comNow = calendar.dateComponents([.year,.month,.day], from: Date()) 

return com.year == comNow.year &;&; com.month == comNow.month 

} 

} 

DateClass

import UIKit 

class DateClass { 

//MARK: - 當(dāng)前時(shí)間相關(guān) 

//MARK: 今年 

static func currentYear() ->Int { 

let calendar = NSCalendar.current 

let com = calendar.dateComponents([.year,.month,.day], from: Date()) 

return com.year! 

} 

//MARK: 今月 

static func currentMonth() ->Int { 

let calendar = NSCalendar.current 

let com = calendar.dateComponents([.year,.month,.day], from: Date()) 

return com.month! 

} 

//MARK: 今日 

static func currentDay() ->Int { 

let calendar = NSCalendar.current 

let com = calendar.dateComponents([.year,.month,.day], from: Date()) 

return com.day! 

} 

//MARK: 今天星期幾 

static func currentWeekDay()->Int{ 

let interval = Int(Date().timeIntervalSince1970) 

let days = Int(interval/86400) // 24*60*60 

let weekday = ((days + 4)%7+7)%7 

return weekday == 0 ? 7 : weekday 

} 

//MARK: 本月天數(shù) 

static func countOfDaysInCurrentMonth() ->Int { 

let calendar = Calendar(identifier:Calendar.Identifier.gregorian) 

let range = (calendar as NSCalendar?)?.range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: Date()) 

return (range?.length)! 

} 

//MARK: 當(dāng)月第一天是星期幾 

static func firstWeekDayInCurrentMonth() ->Int { 

//星期和數(shù)字一一對(duì)應(yīng) 星期日:7 

let dateFormatter = DateFormatter() 

dateFormatter.dateFormat = "yyyy-MM" 

let date = dateFormatter.date(from: String(Date().year())+"-"+String(Date().month())) 

let calender = Calendar(identifier:Calendar.Identifier.gregorian) 

let comps = (calender as NSCalendar?)?.components(NSCalendar.Unit.weekday, from: date!) 

var week = comps?.weekday 

if week == 1 { 

week = 8 

} 

return week! - 1 

} 

//MARK: - 獲取指定日期各種值 

//根據(jù)年月得到某月天數(shù) 

static func getCountOfDaysInMonth(year:Int,month:Int) ->Int{ 

let dateFormatter = DateFormatter() 

dateFormatter.dateFormat = "yyyy-MM" 

let date 

= dateFormatter.date(from: String(year)+"-"+String(month)) 

let calendar = Calendar(identifier:Calendar.Identifier.gregorian) 

let range = (calendar as NSCalendar?)?.range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: date!) 

return (range?.length)! 

} 

//MARK: 根據(jù)年月得到某月第一天是周幾 

static func getfirstWeekDayInMonth(year:Int,month:Int) -> Int{ 

let dateFormatter = DateFormatter() 

dateFormatter.dateFormat = "yyyy-MM" 

let date 

= dateFormatter.date(from: String(year)+"-"+String(month)) 

let calendar = Calendar(identifier:Calendar.Identifier.gregorian) 

let comps = (calendar as NSCalendar?)?.components(NSCalendar.Unit.weekday, from: date!) 

let week = comps?.weekday 

return week! - 1 

} //MARK: date轉(zhuǎn)日期字符串 

static func dateToDateString(_ date:Date, dateFormat:String) -> String { 

let timeZone = NSTimeZone.local 

let formatter = DateFormatter() 

formatter.timeZone = timeZone 

formatter.dateFormat = dateFormat 

let date = formatter.string(from: date) 

return date 

} //MARK: 日期字符串轉(zhuǎn)date 

static func dateStringToDate(_ dateStr:String) ->Date { 

let dateFormatter = DateFormatter() 

dateFormatter.timeZone = TimeZone(abbreviation: "UTC") 

dateFormatter.dateFormat = "yyyy-MM-dd" 

let date 

= dateFormatter.date(from: dateStr) 

return date! 

} 

//MARK: 時(shí)間字符串轉(zhuǎn)date 

static func timeStringToDate(_ dateStr:String) ->Date { 

let dateFormatter = DateFormatter() 

// dateFormatter.timeZone = TimeZone(abbreviation: "UTC") 

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" 

let date 

= dateFormatter.date(from: dateStr) 

return date! 

} 

//MARK: 計(jì)算天數(shù)差 

static func dateDifference(_ dateA:Date, from dateB:Date) -> Double { 

let interval = dateA.timeIntervalSince(dateB) 

return interval/86400 

} 

//MARK: 比較時(shí)間先后 

static func compareOneDay(oneDay:Date, withAnotherDay anotherDay:Date) -> Int { 

let dateFormatter:DateFormatter = DateFormatter() 

dateFormatter.dateFormat = "yyyy-MM-dd" 

let oneDayStr:String = dateFormatter.string(from: oneDay) 

let anotherDayStr:String = dateFormatter.string(from: anotherDay) 

let dateA = dateFormatter.date(from: oneDayStr) 

let dateB = dateFormatter.date(from: anotherDayStr) 

let result:ComparisonResult = (dateA?.compare(dateB!))! 

//Date1 is in the future 

if(result == ComparisonResult.orderedDescending ) { 

return 1 

} 

//Date1 is in the past 

else if(result == ComparisonResult.orderedAscending) { 

return 2 

} 

//Both dates are the same 

else { 

return 0 

} 

} 

//MARK: 時(shí)間與時(shí)間戳之間的轉(zhuǎn)化 

//將時(shí)間轉(zhuǎn)換為時(shí)間戳 

static func stringToTimeStamp(_ stringTime:String)->Int { 

let dfmatter = DateFormatter() 

dfmatter.dateFormat = "yyyy-MM-dd HH:mm:ss" 

dfmatter.locale = Locale.current 

let date = dfmatter.date(from: stringTime) 

let dateStamp:TimeInterval = date!.timeIntervalSince1970 

let dateSt:Int = Int(dateStamp) 

return dateSt 

} 

//將時(shí)間戳轉(zhuǎn)換為年月日 

static func timeStampToString(_ timeStamp:String)->String { 

let string = NSString(string: timeStamp) 

let timeSta:TimeInterval = string.doubleValue 

let dfmatter = DateFormatter() 

dfmatter.dateFormat="yyyy年MM月dd日" 

let date = Date(timeIntervalSince1970: timeSta) 

return dfmatter.string(from: date) 

} 

//將時(shí)間戳轉(zhuǎn)換為具體時(shí)間 

static func timeStampToStringDetail(_ timeStamp:String)->String { 

let string = NSString(string: timeStamp) 

let timeSta:TimeInterval = string.doubleValue 

let dfmatter = DateFormatter() 

dfmatter.dateFormat="yyyy年MM月dd日HH:mm:ss" 

let date = Date(timeIntervalSince1970: timeSta) 

return dfmatter.string(from: date) 

} 

//將時(shí)間戳轉(zhuǎn)換為時(shí)分秒 

static func timeStampToHHMMSS(_ timeStamp:String)->String { 

let string = NSString(string: timeStamp) 

let timeSta:TimeInterval = string.doubleValue 

let dfmatter = DateFormatter() 

dfmatter.dateFormat="HH:mm:ss" 

let date = Date(timeIntervalSince1970: timeSta) 

return dfmatter.string(from: date) 

} 

//獲取系統(tǒng)的當(dāng)前時(shí)間戳 

static func getStamp()->Int{ 

//獲取當(dāng)前時(shí)間戳 

let date = Date() 

let timeInterval:Int = Int(date.timeIntervalSince1970) 

return timeInterval 

} 

//月份數(shù)字轉(zhuǎn)漢字 

static func numberToChina(monthNum:Int) -> String { 

let ChinaArray = ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"] 

let ChinaStr:String = ChinaArray[monthNum - 1] 

return ChinaStr 

} 

//MARK: 數(shù)字前補(bǔ)0 

static func add0BeforeNumber(_ number:Int) -> String { 

if number >= 10 { 

return String(number) 

}else{ 

return "0" + String(number) 

} 

} 

//MARK: 將時(shí)間顯示為(幾分鐘前,幾小時(shí)前,幾天前) 

static func compareCurrentTime(str:String) -> String { 

let timeDate = self.timeStringToDate(str) 

let currentDate = NSDate() 

let timeInterval = currentDate.timeIntervalSince(timeDate) 

var temp:Double = 0 

var result:String = "" 

if timeInterval/60 < 1 { 

result = "剛剛" 

}else if (timeInterval/60) < 60{ 

temp = timeInterval/60 

result = "/(Int(temp))分鐘前" 

}else if timeInterval/60/60 < 24 { 

temp = timeInterval/60/60 

result = "/(Int(temp))小時(shí)前" 

}else if timeInterval/(24 * 60 * 60) < 30 { 

temp = timeInterval / (24 * 60 * 60) 

result = "/(Int(temp))天前" 

}else if timeInterval/(30 * 24 * 60 * 60) < 12 { 

temp = timeInterval/(30 * 24 * 60 * 60) 

result = "/(Int(temp))個(gè)月前" 

}else{ 

temp = timeInterval/(12 * 30 * 24 * 60 * 60) 

result = "/(Int(temp))年前" 

} 

return result 

} 

} 

NSDate 時(shí)差8小時(shí)解決方法

swift 語法 

let date = Date() 

let zone = NSTimeZone.local 

let interval:NSInteger = zone.secondsFromGMT(for: date) 

let now = date.addingTimeInterval(TimeInterval(interval)) 

print(date,now)

} 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末抗愁,一起剝皮案震驚了整個(gè)濱河市溉苛,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌哗讥,老刑警劉巖包颁,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瞻想,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡娩嚼,警方通過查閱死者的電腦和手機(jī)蘑险,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來岳悟,“玉大人佃迄,你說我怎么就攤上這事」笊伲” “怎么了呵俏?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長滔灶。 經(jīng)常有香客問我普碎,道長,這世上最難降的妖魔是什么录平? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任随常,我火速辦了婚禮潜沦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘绪氛。我一直安慰自己唆鸡,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布枣察。 她就那樣靜靜地躺著争占,像睡著了一般。 火紅的嫁衣襯著肌膚如雪序目。 梳的紋絲不亂的頭發(fā)上臂痕,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音猿涨,去河邊找鬼握童。 笑死,一個(gè)胖子當(dāng)著我的面吹牛叛赚,可吹牛的內(nèi)容都是我干的澡绩。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼俺附,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼肥卡!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起事镣,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤步鉴,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后璃哟,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體氛琢,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年随闪,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了艺沼。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蕴掏,死狀恐怖障般,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情盛杰,我是刑警寧澤挽荡,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站即供,受9級(jí)特大地震影響定拟,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一青自、第九天 我趴在偏房一處隱蔽的房頂上張望株依。 院中可真熱鬧,春花似錦延窜、人聲如沸恋腕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽荠藤。三九已至,卻和暖如春获高,著一層夾襖步出監(jiān)牢的瞬間哈肖,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來泰國打工念秧, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留淤井,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓摊趾,卻偏偏與公主長得像币狠,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子严就,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容