时间日期
NSDate
在Objective-C中,可以使用如下的代码创建一个UTC的时间:
NSDate *currentUTCDate = [NSDate date]
但是在Swift中,如果使用如下方式:
let date = NSDate()
获取到的会是本地时间。
UTC时间与本地化时间
import UIKit let date = NSDate(); // "Apr 1,2015,8:53 AM" <-- local without seconds var formatter = NSDateFormatter(); formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"; let defaultTimeZoneStr = formatter.stringFromDate(date); // "2015-04-01 08:52:00 -0400" <-- same date,local,but with seconds formatter.timeZone = NSTimeZone(abbreviation: "UTC"); let utcTimeZoneStr = formatter.stringFromDate(date); // "2015-04-01 12:52:00 +0000" <-- same date,now in UTC
时间比较
如果需要比较两个日期,可以使用如下方法,在如下代码中已经展示了如何处理不同的返回结果:
// Date comparision to compare current date and end date. var dateComparisionResult:NSComparisonResult = NSDate().compare(endDate) if dateComparisionResult == NSComparisonResult.OrderedAscending { // Current date is smaller than end date. } else if dateComparisionResult == NSComparisonResult.OrderedDescending { // Current date is greater than end date. } else if dateComparisionResult == NSComparisonResult.OrderedSame { // Current date and end date are same. }
TimeStamp
如果需要将某个TimeStamp("/Date(1427909016000-0800)”)转化为NSDate对象,那么可以使用如下的扩展工具,该扩展将会把TimeStamp转化为本地化时间。其中1427909016000表示从Unix计时以来的毫秒数,而-0800表示时区:
extension NSDate { convenience init?(jsonDate: String) { 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. self.init(timeIntervalSince1970: timeStamp) return } } } // Wrong format,return nil. (The compiler requires us to // do an initialization first.) self.init(timeIntervalSince1970: 0) return nil } }
使用的例子如下:
if let theDate = NSDate(jsonDate: "/Date(1427909016000-0800)/") { println(theDate) } else { println("wrong format") }
NSDateFormatter:格式化时间
var dataString = "April 1,2015" as String var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy" dateFormatter.timeZone = NSTimeZone.localTimeZone() // convert string into date let dateValue = dateFormatter.dateFromString(dataString) as NSDate! println(dateValue)
NSCalendar
// Playground - noun: a place where people can play import UIKit // Setup the calendar object let calendar = NSCalendar.currentCalendar() // Set up date object let date = NSDate() // Create an NSDate for the first and last day of the month //let components = calendar.components(NSCalendarUnit.CalendarUnitYear | // NSCalendarUnit.CalendarUnitMonth | // NSCalendarUnit.WeekdayCalendarUnit | // NSCalendarUnit.WeekCalendarUnit | // NSCalendarUnit.CalendarUnitDay,// fromDate: date) // Create an NSDate for the first and last day of the month let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth,fromDate: date) components.month // Getting the First and Last date of the month components.day = 1 let firstDateOfMonth: NSDate = calendar.dateFromComponents(components)! components.month += 1 components.day = 0 let lastDateOfMonth: NSDate = calendar.dateFromComponents(components)! var unitFlags = NSCalendarUnit.WeekOfMonthCalendarUnit | NSCalendarUnit.WeekdayCalendarUnit | NSCalendarUnit.CalendarUnitDay let firstDateComponents = calendar.components(unitFlags,fromDate: firstDateOfMonth) let lastDateComponents = calendar.components(unitFlags,fromDate: lastDateOfMonth) // Sun = 1,Sat = 7 let firstWeek = firstDateComponents.weekOfMonth let lastWeek = lastDateComponents.weekOfMonth let numOfDatesToPrepend = firstDateComponents.weekday - 1 let numOfDatesToAppend = 7 - lastDateComponents.weekday + (6 - lastDateComponents.weekOfMonth) * 7 let startDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay,value: -numOfDatesToPrepend,toDate: firstDateOfMonth,options: nil)! let endDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay,value: numOfDatesToAppend,toDate: lastDateOfMonth,options: nil)! Array(map(0..<42) { calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay,value: $0,toDate: startDate,options: nil)! }) "\(components.year)" var dateString = "2014-10-3" // change to your date format var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "YYYY-MM-dd" var someDate = dateFormatter.dateFromString(dateString) println(someDate)