gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:03:53 25 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/31337768/

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