Swift 的 NSDate 初学者指南

移动开发 作者: 2024-08-22 19:20:01
译者:ray16897188;校对:numbbbbb;定稿:Cee 如果问我在做过的所有项目中做的最多的事情,那处理日期绝对是榜上有名(译注:本文中的「日期」是指代 NSDate 对象,同时包含「日(date)」 和「时(time)」这两个元素)。毋庸置疑,无论工作量是多是少,开发者迟早需要「玩」一下 NSDate 类,去按某种方式处理一下日期。从简单的将一个日期转换成一个字符串到对日期做计算,总

关于 Demo App

基本概念

let dateComponents = NSDateComponents()
let day = dateComponents.day
let month = dateComponents.month

NSDate 和 String 之间的转换

let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.locale = NSLocale(localeIdentifier: "el_GR")
dateFormatter.locale = NSLocale(localeIdentifier: "fr_FR")

用 Date formatter styles 为输出结果设置格式

dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
var convertedDate = dateFormatter.stringFromDate(currentDate)
dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
convertedDate = dateFormatter.stringFromDate(currentDate)
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
convertedDate = dateFormatter.stringFromDate(currentDate)
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
convertedDate = dateFormatter.stringFromDate(currentDate)

使用 Date format specifier

dateFormatter.dateFormat = "EEEE,MMMM dd,yyyy"
convertedDate = dateFormatter.stringFromDate(currentDate)
dateFormatter.dateFormat = "HH:mm:ss"
convertedDate = dateFormatter.stringFromDate(currentDate)
var dateAsString = "24-12-2015 23:59"
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
var newDate = dateFormatter.dateFromString(dateAsString)
dateAsString = "Thu,08 Oct 2015 09:22:33 GMT"
dateFormatter.dateFormat = "EEE,dd MMM yyyy HH:mm:ss zzz"
newDate = dateFormatter.dateFromString(dateAsString)

使用 NSDateComponents

let calendar = NSCalendar.currentCalendar()
let dateComponents = calendar.components([NSCalendarUnit.Day,NSCalendarUnit.Month,NSCalendarUnit.Year,NSCalendarUnit.WeekOfYear,NSCalendarUnit.Hour,NSCalendarUnit.Minute,NSCalendarUnit.Second,NSCalendarUnit.Nanosecond],fromDate: currentDate)

print("day = \(dateComponents.day)","month = \(dateComponents.month)","year = \(dateComponents.year)","week of year = \(dateComponents.weekOfYear)","hour = \(dateComponents.hour)","minute = \(dateComponents.minute)","second = \(dateComponents.second)","nanosecond = \(dateComponents.nanosecond)",separator: ",",terminator: "")
let components = NSDateComponents()
components.day = 5
components.month = 01
components.year = 2016
components.hour = 19
components.minute = 30
newDate = calendar.dateFromComponents(components)
components.timeZone = NSTimeZone(abbreviation: "GMT")
newDate = calendar.dateFromComponents(components)

components.timeZone = NSTimeZone(abbreviation: "CST")
newDate = calendar.dateFromComponents(components)

components.timeZone = NSTimeZone(abbreviation: "CET")
newDate = calendar.dateFromComponents(components)

比较日期和时间

dateFormatter.dateFormat = "MMM dd,yyyy zzz"
dateAsString = "Oct 08,2015 GMT"
var date1 = dateFormatter.dateFromString(dateAsString)!

dateAsString = "Oct 10,2015 GMT"
var date2 = dateFormatter.dateFromString(dateAsString)!
// Comparing dates - Method #1
print("Earlier date is: \(date1.earlierDate(date2))")
print("Later date is: \(date1.laterDate(date2))")
// Comparing dates - Method #2
if date1.compare(date2) == NSComparisonResult.OrderedDescending {
    print("Date1 is Later than Date2")
}
else if date1.compare(date2) == NSComparisonResult.OrderedAscending {
    print("Date1 is Earlier than Date2")
}
else if date1.compare(date2) == NSComparisonResult.OrderedSame {
    print("Same dates")
}
// Comparing dates - Method #3
if date1.timeIntervalSinceReferenceDate > date2.timeIntervalSinceReferenceDate {
    print("Date1 is Later than Date2")
}
else if date1.timeIntervalSinceReferenceDate <  date2.timeIntervalSinceReferenceDate {
    print("Date1 is Earlier than Date2")
}
else {
    print("Same dates")
}
// Comparing time.
dateFormatter.dateFormat = "HH:mm:ss zzz"
dateAsString = "14:28:16 GMT"
date1 = dateFormatter.dateFromString(dateAsString)!

dateAsString = "19:53:12 GMT"
date2 = dateFormatter.dateFromString(dateAsString)!

if date1.earlierDate(date2) == date1 {
    if date1.isEqualToDate(date2) {
        print("Same time")
    }
    else {
        print("\(date1) is earlier than \(date2)")
    }
}
else {
    print("\(date2) is earlier than \(date1)")
}

计算出未来或过去的日期

let monthsToAdd = 2
let daysToAdd = 5
var calculatedDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.Month,value: monthsToAdd,toDate: currentDate,options: NSCalendarOptions.init(rawValue: 0))
calculatedDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.Day,value: daysToAdd,toDate: calculatedDate!,options: NSCalendarOptions.init(rawValue: 0))
let newDateComponents = NSDateComponents()
newDateComponents.month = monthsToAdd
newDateComponents.day = daysToAdd

calculatedDate = NSCalendar.currentCalendar().dateByAddingComponents(newDateComponents,options: NSCalendarOptions.init(rawValue: 0))
let hoursToAddInSeconds: NSTimeInterval = 90 * 60
calculatedDate = currentDate.dateByAddingTimeInterval(hoursToAddInSeconds)
let numberOfDays = -5684718
calculatedDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.Day,value: numberOfDays,options: NSCalendarOptions.init(rawValue: 0))

dateFormatter.dateFormat = "EEEE,MMM dd,yyyy GGG"
dateAsString = dateFormatter.stringFromDate(calculatedDate!)

计算出日期的差值

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateAsString = "2015-10-08 14:25:37"
date1 = dateFormatter.dateFromString(dateAsString)!

dateAsString = "2018-03-05 08:14:19"
date2 = dateFormatter.dateFromString(dateAsString)!
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66829.html
swift nsdate 初学者 指南