objective-c - 如何在午夜获取今天的 NSDate 对象?

标签 objective-c cocoa-touch nsdate

获取表示当天午夜的 NSDate 对象的最有效方法是什么?

最佳答案

iOS 8 中的新 API

iOS 8 在 NSCalendar 上包含一个名为 startOfDayForDate 的新方法,它非常易于使用:

let startOfToday = NSCalendar.currentCalendar().startOfDayForDate(NSDate())

苹果的描述:

This API returns the first moment date of a given date. Pass in [NSDate date], for example, if you want the start of "today". If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist.

关于时区的更新:

因为 startOfDayForDate 是 NSCalendar 上的一个方法,它使用 NSCalendar 的时区。因此,如果我想查看洛杉矶今天开始时纽约的时间,我可以这样做:

let losAngelesCalendar = NSCalendar.currentCalendar().copy() as! NSCalendar
losAngelesCalendar.timeZone = NSTimeZone(name: "America/Los_Angeles")!

let dateTodayBeganInLosAngeles = losAngelesCalendar.startOfDayForDate(NSDate())
dateTodayBeganInLosAngeles.timeIntervalSince1970

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .ShortStyle
dateFormatter.timeZone = NSTimeZone(name: "America/New_York")!
let timeInNewYorkWhenTodayBeganInLosAngeles = dateFormatter.stringFromDate(dateTodayBeganInLosAngeles)
print(timeInNewYorkWhenTodayBeganInLosAngeles) // prints "Jul 29, 2015, 3:00 AM"

关于objective-c - 如何在午夜获取今天的 NSDate 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31337768/

相关文章:

ios - 从 UIImage 设置 SKSpriteNode

ios - 无法在 xib 中设置 View socket

iphone - 如何自定义EKEventViewController的UITableView?

ios - 如何在 Swift 中使用 UIDatePicker 仅在没有日期组件的情况下将时间存储在 CoreData 中?

ios - PFObject 子类,无法识别的选择器发送到自定义方法的实例

iphone - TestFlight:应用程序可执行文件包含不受支持的架构:armv7s

objective-c - NSDateFormatter doesRelativeDateFormatting 返回意外的相对日期值

ios - NSData 转换时堆缓冲区溢出

ios - 使用 NSDateComponents/NSCalendar 破译一个月中的几周

swift - 以正确的方式从 Int 构造日期