让nsdata使屏幕变黑(晚上时间观看)迅速 - Getting an NSDate to change the screen to black (night time viewing) Swift

- 此内容更新于:2015-12-20
主题:

我想让时间使用NSDate为了改变应用程序的背景黑色的夜晚。我怎么去呢?我要看什么时候带人在(如果可能的话),或者我可以问对方在NSUserDefaults并存储它。什么好主意吗?

原文:

I am trying to get the time using NSDate in order to change the background of the app to black at night. How would I go about that? I need to see what time zone the person is in (if possible) or I could ask the person and store it in NSUserDefaults. Any ideas?

解决方案:
“黑暗”是一个相对的概念。一天的长度可以极大地取决于用户的位置和时间。精确定义的黑,需要一天的日出日落时间的气象服务。但是如果你想要一些简单的,说7点-6点是黑暗,试试这个:
原文:

"Dark" is a relative term. Day length can vary significantly depending on the user's location and the time of year. To get precise definition of dark, you need to get the sunrise and sunset times for the day from a weather service.

But if you want something simple, say 7PM - 6AM is dark, try this:

let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let dateComponents = calendar.componentsInTimeZone(NSTimeZone.defaultTimeZone(), fromDate: NSDate())

let isDark = dateComponents.hour >= 19 || dateComponents.hour <= 6