【问题标题】:How do you compare current time with specified times (to determine Open/Closed)?您如何将当前时间与指定时间进行比较(以确定打开/关闭时间)?
【发布时间】:2023-03-31 17:07:01
【问题描述】:

我正在为不同的夜总会和酒吧制作应用程序,我想添加这些夜总会和酒吧的开放和关闭时间。如何检查用户 iPhone 上的当前时间是否在营业时间内?

例如,营业时间为 22-03 / 10PM-3AM:
当前时间 22:01 -> 打开
当前时间 03:01 -> 关闭

对不起,如果我没有把问题说得足够清楚,但我会很感激任何答案 =)

【问题讨论】:

  • 阅读 NSDate、NSDateFormatter、NSCalendar 和 NSDateComponents 的文档。很容易有 5 种不同的方式来做你想做的事。
  • Xcode 是一个IDE/设计环境;不要将其与 Objective-C 语言或适用的运行时混淆
  • 懒惰,我会做的是将时间安排为24小时制,例如“22:30”,使用NSDateFormatter将当前时间格式化为“HH:mm”,并进行字符串比较. (其他人会使用复杂的 NSDateComponents 东西。)

标签: ios objective-c


【解决方案1】:

正如其他人所提到的,有不同的方法可以做到这一点,您应该参考 Apple 文档以了解如何使用 NSDate 以及用于处理日期的各种其他类。

但是为了快速提供帮助,我没有尝试过(我只是直接在文本框中写了它),但这应该适合你。您将使用比较来查看当前时间是否小于或大于另一个时间:

NSDate* openTime...;
NSDate* closeTime...
NSDate* now = [NSDate date];

NSComparisonResult result = [openTime compare:now];

if(result == NSOrderedDescending)
{
    NSLog(@"Now takes place before the opening time."); 
}
else if(result == NSOrderedAscending)
{
    NSLog(@"Now takes place after the opening time."); 
}
else
{
    NSLog(@"Now and opening time are the same.");
}


result = [closeTime compare:now];

if(result == NSOrderedDescending)
{
    NSLog(@"Now takes place before the closing time."); 
}
else if(result == NSOrderedAscending)
{
    NSLog(@"Now takes place after the closing time."); 
}
else
{
    NSLog(@"Now and closing time are the same.");
}

【讨论】:

  • 这样的问题是NSDate代表的是一个特定的日子,所以你必须每天重新计算开盘和收盘的时间。
  • 确实如此,我没想到。
  • 我必须在咖啡馆关门前去上班,但我会在回来后及时更新答案。
  • 不,关门时间是上周。
猜你喜欢
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 2015-02-24
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多