【问题标题】:Compare a string with current time将字符串与当前时间进行比较
【发布时间】:2015-12-05 22:55:00
【问题描述】:

我有一个带有特定小时-分钟时间戳的字符串,如下所示:

let timeToday = "14:00"

我想将此时间与当天的当前时间进行比较。我在使用 NSDate 以及它使用 UTC 时间戳这一事实时遇到问题。我之前没有使用过NSDateNSCalendarNSDateFormatter,我对解决这个看似简单的任务有多么困难感到有点沮丧......

所以我试图将字符串和当前时间的相同时间设置为两个 NSDate 变量,然后使用某种比较方法,但我似乎无法在相同的基础上得到它们。

如何在同一个基础上获取两个时间戳?

所以我有一个 NSDate:

NSDate: timeToday     // "2015-12-05 14:00:00 +0000"
NSDate: currentTime   // "2015-12-05 22:46:54 +0000"

【问题讨论】:

  • +0000 表示 UTC 时间
  • 我不明白你在问什么。起初我以为您是在说您想将看起来像“14:00”的时间字符串视为当天的时间和当前用户的时区。在这种情况下,您将创建一个 NSDateFormatter 并向其提供格式字符串“HH:mm”,然后使用dateFromString() 简单地将时间字符串转换为日期。您可以使用相同的日期格式化程序将当前日期显示为时间字符串,这次使用 stringFromDate()
  • 你需要咬紧牙关阅读 NSDate、NSDateFormatter、NSCalendar,尤其是 NSCalendar 文档中关于“日历计算”的部分。那部分真的很有帮助。这东西很复杂而且有点混乱,需要相当深入的研究才能“grok”它。

标签: ios swift nsdate nsdateformatter


【解决方案1】:

所以我最终通读了文档以了解数据类型的含义。 NSDate 代表一个时间点,根据您在地球上的位置,它的显示方式会有所不同。因此,使用 UTC 作为时间字符串和当前时间的基础是完全可以的。

我解决了这样的问题,使用:

let calender = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
calender!.locale = NSLocale.currentLocale()

let timeToday = "14:00"
let timeArray = timeToday.componentsSeparatedByString(":")
let timeTodayHours = Int(timeArray[0])
let timeTodayMin = Int(timeArray[1])
let timeTodayDate = calender!.dateBySettingHour(timeTodayHours!, minute: timeTodayMin!, second: 00, ofDate: NSDate(), options: NSCalendarOptions())

let now = NSDate()
if now.compare(timeTodayDate!) == .OrderedDescending {
    print(" 'timeToday' has passed!!! ")
}

【讨论】:

  • 你也可以尝试使用 NSDateComponents 并在上面设置小时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多