https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/index.html
// 當地日期時間,沒有秒。ex : "May 25, 2015, 11:30 AM"
let date = NSDate()
// 格式化
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
let defaultTimeZonStr = formatter.stringFromDate(date) // 同樣的日期時間,但是有秒。ex : "2015-05-25 11:34:21 +0800"
formatter.timeZone = NSTimeZone(abbreviation: "UTC")
let utcTimeZoneStr = formatter.stringFromDate(date) // 同樣的日期時間,但是在UTC。ex : "2015-05-25 03:34:21 +0000"
// 設定日期
var endDate = NSDate().dateByAddingTimeInterval(30 * 60) // 30 minutes from current time
// 日期比較
var dateComparisionResult:NSComparisonResult = NSDate().compare(endDate)
if dateComparisionResult == NSComparisonResult.OrderedAscending
{
println("當前日期時間比 end date 小.") // 這個範例中,這個結果會被打印出來
}
else if dateComparisionResult == NSComparisonResult.OrderedDescending
{
println("當前日期時間比 end date 大.")
}
else if dateComparisionResult == NSComparisonResult.OrderedSame
{
println("當前日期時間與 end date 相同.")
}
// iOS 8.0+ 的 NSCalendar 方法
var cal = NSCalendar.currentCalendar()
cal.startOfDayForDate(endDate) // 忽略時間元素,ex : "May 25, 2015, 12:00 AM"
cal.isDateInToday(endDate) // 指定日期是否為今天。其他的還有
cal.isDateInTomorrow(endDate)
cal.isDate(NSDate(), inSameDayAsDate: endDate) // 比對兩個日期是否相同
// 字串轉為日期
var dataString = "April 1, 2015" as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let dateValue = dateFormatter.dateFromString(dataString) as NSDate!
println(dateValue) // ex : "Apr 1, 2015, 12:00 AM"
格式化:
類似“/Date(1427909016000-0800)”格式的timestamp,要轉成NSDate:
func timestampToNSDate(jsonDate: String) -> NSDate? {
let prefix = "/Date("
let suffix = ")/"
let scanner = NSScanner(string: jsonDate)
// Check prefix:
if scanner.scanString(prefix, intoString: nil) {
// Read milliseconds part:
var milliseconds : Int64 = 0
if scanner.scanLongLong(&milliseconds) {
// Milliseconds to seconds:
var timeStamp = NSTimeInterval(milliseconds)/1000.0
// Read optional timezone part:
var timeZoneOffset : Int = 0
if scanner.scanInteger(&timeZoneOffset) {
let hours = timeZoneOffset / 100
let minutes = timeZoneOffset % 100
// Adjust timestamp according to timezone:
timeStamp += NSTimeInterval(3600 * hours + 60 * minutes)
}
// Check suffix:
if scanner.scanString(suffix, intoString: nil) {
// Success! Create NSDate and return.
return NSDate(timeIntervalSince1970: timeStamp)
}
}
}
return nil
}
timestampToNSDate("/Date(1427909016000-0800)/")