在Objective-C中,可以使用如下的代码创建一个UTC的时间:
NSDate *currentUTcdate = [NSDate date]
但是在Swift中,如果使用如下方式:
let date = NSDate()
获取到的会是本地时间。
UTC时间与本地化时间import UIKitlet date = NSDate();// "Apr 1,2015,8:53 AM" <-- local without secondsvar 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 secondsformatter.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 Stringvar dateFormatter = NSDateFormatter()dateFormatter.dateFormat = "MM-dd-yyyy"dateFormatter.timeZone = NSTimeZone.localTimeZone()// convert string into datelet dateValue = dateFormatter.dateFromString(dataString) as NSDate!println(dateValue)
NSCalendar
// Playground - noun: a place where people can playimport UIKit// Setup the calendar objectlet calendar = NSCalendar.currentCalendar()// Set up date objectlet 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 monthlet components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth,fromDate: date)components.month// Getting the First and Last date of the monthcomponents.day = 1let firstDateOfMonth: NSDate = calendar.dateFromComponents(components)!components.month += 1components.day = 0let lastDateOfMonth: NSDate = calendar.dateFromComponents(components)!var unitFlags = NSCalendarUnit.WeekOfMonthCalendarUnit | NSCalendarUnit.WeekdayCalendarUnit | NSCalendarUnit.CalendarUnitDaylet firstDateComponents = calendar.components(unitFlags,fromDate: firstDateOfMonth)let lastDateComponents = calendar.components(unitFlags,fromDate: lastDateOfMonth)// Sun = 1,Sat = 7let firstWeek = firstDateComponents.weekOfMonthlet lastWeek = lastDateComponents.weekOfMonthlet numOfDatestoprepend = firstDateComponents.weekday - 1let numOfDatesToAppend = 7 - lastDateComponents.weekday + (6 - lastDateComponents.weekOfMonth) * 7let 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: ,toDate: startDate,options: nil)!})"\(components.year)"var dateString = "2014-10-3" // change to your date formatvar dateFormatter = NSDateFormatter()dateFormatter.dateFormat = "YYYY-MM-dd"var someDate = dateFormatter.dateFromString(dateString)println(someDate)总结
以上是内存溢出为你收集整理的Swift&Cocoa实战之数据类型:时间日期全部内容,希望文章能够帮你解决Swift&Cocoa实战之数据类型:时间日期所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)