我使用的是openweathermap.org api。我正在获得日出和日落日期并比较这些。 date1是日出,date2是日落日期。我检查天气是否真实,答案是肯定的。但答案是错误的。我比较月,日和时间。我的代码有什么问题?
这是我的代码:
func checkDate(date1:NSDate, date2:NSDate){
// Date comparision to compare current date and end date.
var dateComparisionResult:NSComparisonResult = NSDate().compare(date1)
var dateComparision:NSComparisonResult = NSDate().compare(date2)
if dateComparisionResult == NSComparisonResult.OrderedDescending || dateComparisionResult == NSComparisonResult.OrderedSame && dateComparision == NSComparisonResult.OrderedAscending
{
//result is
answerLabel.text = "yes".uppercaseString
self.view.backgroundColor = UIColor.whiteColor()
answerLabel.textColor = UIColor.blackColor()
}else{
answerLabel.text = "no".uppercaseString
self.view.backgroundColor = UIColor.blackColor()
answerLabel.textColor = UIColor.whiteColor()
}
}
答案 0 :(得分:1)
根据评论,您似乎只是在检查当前时间是否在白天。
所以,首先,不要只是简单地只检查现在,而是让它成为NSDate()
扩展名,可以随时应用。
extension NSDate {
func between(firstDate: NSDate, _ secondDate: NSDate) -> Bool {
// TODO: determine if self is between first and second date
}
}
为了使这更容易阅读,让我们为NSDate
提出一些方便的重载运算符,对吗?
func == (left: NSDate, right: NSDate) {
return left.compare(right) == .OrderedSame
}
func > (left: NSDate, right: NSDate) {
return left.compare(right) == .OrderedDescending
}
func < (left: NSDate, right: NSDate) {
return left.compare(right) == .OrderedAscending
}
func != (left: NSDate, right: NSDate) {
return !(left == right)
}
func >= (left: NSDate, right: NSDate) {
return (left == right) || (left > right)
}
func <= (left: NSDate, right: NSDate) {
return (left == right) || (left < right)
}
现在我们已准备好回到我们提出的between
方法,现在变得非常简单:
extension NSDate: Equatable, Comparable {
func between(firstDate: NSDate, _ secondDate: NSDate) -> Bool {
return self >= firstDate && self <= secondDate
}
}
我们是否想要“或等于”比较符合我们的具体要求。但是添加运算符使得它更加清晰,并为我们在其他场景中使用添加了方便的运算符,而且编写单元测试要好得多。作为额外的奖励,我们现在可以将NSDate
声明为conforming to Equatable
and Comparable
。
现在,确定白天的特定时间是否如此简单:
let isDaylight = NSDate().between(sunrise, sunset)
或者也许:
if NSDate().between(sunrise, sunset) {
// daylight
} else {
// not daylight
}
答案 1 :(得分:0)
我编辑了这样的代码并且有效!
代码:
func checkDate(date1:NSDate, date2:NSDate){
// Date comparision to compare current date and end date.
var dateComparisionResult:NSComparisonResult = NSDate().compare(date1)
var dateComparision:NSComparisonResult = NSDate().compare(date2)
if dateComparisionResult == NSComparisonResult.OrderedSame || dateComparisionResult == NSComparisonResult.OrderedDescending && dateComparision == NSComparisonResult.OrderedAscending
{
//if It is daylight outside
answerLabel.text = "yes".uppercaseString
self.view.backgroundColor = UIColor.whiteColor()
answerLabel.textColor = UIColor.blackColor()
}else{
//if It's not daylight outside
answerLabel.text = "no".uppercaseString
self.view.backgroundColor = UIColor.blackColor()
answerLabel.textColor = UIColor.whiteColor()
}
}