Swift編程(七):全面學(xué)習(xí)NSDate的相關(guān)知識

個人項目

個人站點(diǎn):<a >LN電影網(wǎng)</a>
個人博客:<a >L&N博客</a>

寫在前面

歡迎大家關(guān)注我的個人博客:<a >博客地址</a>,這里主要是我在個人開發(fā)時候遇到的坑和挖完的坑,包括 PHP CentOS 以及 Swift 等相關(guān)只是

最近一直在搞崗位競聘,雖然沒有成功,但也算一次不錯的經(jīng)歷,有些東西還是要看開些比較好;好啦,一個多周沒有碰Swift手有點(diǎn)生,找了一個關(guān)于日期教程學(xué)習(xí)整理了一下(靈感來自:swift.gg)
其實這篇博文準(zhǔn)備寫很久了,奈何工作確實有點(diǎn)忙,搞得自己有點(diǎn)暈頭轉(zhuǎn)向,后面還有一個關(guān)于NSDate的拓展庫,我會在后面的博客中寫出來教大家如何深入學(xué)習(xí)NSDate的實戰(zhàn)開發(fā)。
下面就開始寫吧。

目標(biāo):

  • 認(rèn)識NSDate
  • 學(xué)習(xí)NSDateFormatter
  • 學(xué)習(xí)NSCalendar和NSDateComponents
  • 學(xué)習(xí)日期比較和計算

學(xué)習(xí)NSDate

1.一個簡單的NSDate

<pre>```
//獲取當(dāng)前時間
let currentDate = NSDate()


####2.NSDateFormatter的介紹
NSDate <--> String轉(zhuǎn)換(dateFromString和stringFromDate),并且可以設(shè)置NSDate輸出的多種屬性:日期區(qū)域、日期格式(完整或省略格式)和日期形式(2015年-12月19日 或 2015-12-19 01:11等展示形式)


 - 設(shè)置區(qū)域(locale)

<pre>```
let dateFormatter = NSDateFormatter()
//設(shè)置locale兩種方式:
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.locale = NSLocale(localeIdentifier: "el_GR")//希臘
```</pre>

 - 設(shè)置日期格式(NSDateFormatterStyle)

<pre>```
//設(shè)置格式為FullStyle,然后轉(zhuǎn)換成String類型
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
var convertedDate = dateFormatter.stringFromDate(currentDate)
/*
NSDateFormatterStyle枚舉類型:
FullStyle格式:"Saturday, December 19, 2015"
LongStyle格式:"December 19, 2015"
MediumStyle格式:"Dec 19, 2015"
ShortStyle格式:"12/19/15"
*/
```</pre>

 - 設(shè)置日期形式(dateFormat)

>各種字符的描述(重要)
EEEE: 表示星期(如:Saturday)。使用1-3個字母(E)表示星期的縮寫(Sat)
MMMM: 月份全寫(如:December)。使用3個字母(M)表示月份的縮寫(Dec),使用1-2個字母(M)表示數(shù)字月份
dd: 表示一個月里面日期的數(shù)字(09 和 15)
yyyy: 4個數(shù)字表示年(如2015)
HH: 2個數(shù)字表示小時(如:08 或 19)
mm: 2個數(shù)字表示分鐘(如:05 或 54)
ss: 2個數(shù)字表示秒
zzz: 3個字母表示時區(qū)

<pre>```
dateFormatter.dateFormat = "yyyy-MM-dd MMMM EEEE"
let convertedDate = dateFormatter.stringFromDate(currentDate)
//展示結(jié)果:"2015-12-19 December Saturday"

dateFormatter.dateFormat = "yyyy-MM-dd MMM EEE"
convertedDate = dateFormatter.stringFromDate(currentDate)
//展示結(jié)果:"2015-12-19 Dec Sat"

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
convertedDate = dateFormatter.stringFromDate(currentDate)
//展示結(jié)果:"2015-12-19 01:31:54"

```</pre>

- dateFromString的使用

>上面的操作都是設(shè)置NSDate的格式使用stringFromDate方法,獲得對應(yīng)字符串(String)下面通過dateFromString活的NSDate

<pre>```
//注意設(shè)置的日期格式要跟字符串的日期格式保持一致
var dateAsString = "2015-12-15 09:14"
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
var newDate = dateFormatter.dateFromString(dateAsString)
//展示結(jié)果:"Dec 15, 2015, 9:14 AM"
```</pre>

####3.NSDateComponents介紹

- 介紹各種日期組件

<pre>```
/*
Year: 年
Month: 月
Weekday:星期
Day:日
Hour: 時
Minute: 分
Second: 秒
Nanoscond:微秒
WeekOfYear:一年中的第幾個星期
WeekOfMonth:一個月中的第幾個星期
WeekdayOrdinal:未知
*/
```</pre>

- NSCalendar介紹

>NSCalendar:實現(xiàn)NSDate到NSDateComponents對象的轉(zhuǎn)換

- 實現(xiàn)NSDate -->NSDateComponents

<pre>```
let calendar = NSCalendar.currentCalendar()
let dateComponents = calendar.components([NSCalendarUnit.Day,NSCalendarUnit.Month,NSCalendarUnit.Year,NSCalendarUnit.WeekOfYear,NSCalendarUnit.Hour,NSCalendarUnit.Minute,NSCalendarUnit.Second,NSCalendarUnit.Nanosecond,NSCalendarUnit.Weekday], fromDate: currentDate)
//這樣可以查看當(dāng)前日期Day/Month/Year/WeekOfYear/Hour/Minute/Second/NanoSecond/Weekday信息
print("年=\(dateComponents.year),月=\(dateComponents.month),日=\(dateComponents.day),小時=\(dateComponents.hour),分鐘=\(dateComponents.minute),秒=\(dateComponents.second),微秒=\(dateComponents.nanosecond),一年中第\(dateComponents.weekOfYear)個星期,今天是星期\(dateComponents.weekday-1)")
//打印結(jié)果:"年=2015,月=12,日=19,小時=1,分鐘=50,秒=48,微秒=663465976,一年中第51個星期,今天是星期6\n"

```</pre>

- 實現(xiàn)NSDateComponents --> NSDate

<pre>```
let components = NSDateComponents()
components.year = 2015
components.month = 12
components.day = 15
components.hour = 09
components.minute = 58
let newDate = calendar.dateFromComponents(components)
//結(jié)果展示:"Dec 15, 2015, 11:58 PM"
```</pre>

####4.日期比較

我主要推薦兩種官方方式:(earlierDate與laterDate)和compare

- 兩種方式創(chuàng)建日期

<pre>```
//結(jié)合前面學(xué)到的使用NSDateFormatter和NSCalendar創(chuàng)建兩個時間
//方式一:NSCalendar
let newCalendar = NSCalendar.currentCalendar()
let newComponents = NSDateComponents()
newComponents.year = 2015
newComponents.month = 12
newComponents.day = 20
newComponents.hour = 11
newComponents.minute = 55
newComponents.second = 11
let newDate1 = newCalendar.dateFromComponents(newComponents)!
//方式二:NSDateFormatter
let newDateFormatter = NSDateFormatter()
newDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let newDateString = "2015-12-20 11:55:11"
let newDate2 = newDateFormatter.dateFromString(newDateString)!
```</pre>

- earlierDate與laterDate實現(xiàn)比較

>原理:
earlierDate:
1.如果date1對象比date2早,那么返回date1,反之返回date2
2.如果兩者相等,則返回date1
laterDate:反之

<pre>```
if newDate1 == newDate1.earlierDate(newDate2){
    print("newDate1不晚于newDate2")
} else {
    print("newDate1晚于newDate2")
}

if newDate1 == newDate1.laterDate(newDate2) {
    print("newDate1不早于newDate2")
} else {
    print("newDate1早于newDate2")
}
```</pre>

>很明顯上面兩個事件相等,則返回值是"newDate1不晚于newDate2"和"newDate1不早于newDate2"
如果講上面的newComponents.second = 10,這樣明顯就是newDate1早了,在看下結(jié)果:"newDate1不晚于newDate2\n"和"newDate1比newDate2早\n"

- compare方法

>原理:newDate1.compare(newDate2)得到的結(jié)果是一個NSComparisonResult枚舉類型中的元素
NSComparisonResult:
OrderedDescending:降序,說明前一個時間大
OrderedAscending:升序,說明前一個時間小
OrderedSame:相等,時間相同

<pre>```
if newDate1.compare(newDate2) == NSComparisonResult.OrderedDescending {
    print("newDate1比newDate2晚")
}else if newDate1.compare(newDate2) == NSComparisonResult.OrderedAscending {
    print("newDate1比newDate2早")
}else if newDate1.compare(newDate2) == NSComparisonResult.OrderedSame {
    print("newDate1與newDate2同時")
}
```</pre>

####4.時間計算

>先簡單看一個添加月份的例子

<pre>```
let currentDate = NSDate() //當(dāng)前時間
let monthsToAdd = 2
var calculatedDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.Month, 
value: monthsToAdd, toDate: currentDate, options: NSCalendarOptions.init(rawValue: 0))
//結(jié)果是:相對于currentDate兩個月以后的時間
```</pre>

####5.事件差計算

>我們使用上面創(chuàng)建的兩個時間newDate1 和 newDate2

<pre>```
var diffDateComponents =  NSCalendar.currentCalendar().components([NSCalendarUnit.Year, 
                          NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, 
                          NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: newDate1, 
                          toDate: newDate2, options: NSCalendarOptions.init(rawValue: 0))

//然后將diffDateComponents的year/day/hour/minute/second打印出來即可
```</pre>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容