gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:29:25 24 4
gpt4 key购买 nike

获取代表当天午夜的 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/9040319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com