【问题标题】:How do I make this code show days until the event, not days since the event如何使此代码显示事件发生前的天数,而不是事件发生后的天数
【发布时间】:2015-10-07 04:14:13
【问题描述】:

我有以下代码:

//Age

@IBOutlet weak var daysLabel: UILabel!
@IBOutlet weak var monthsLabel: UILabel!
@IBOutlet weak var yearsLabel: UILabel!

@IBAction func birthday(sender:AnyObject){
    var dateComponents = NSDateComponents()

    dateComponents.day = 19
    dateComponents.month = 12
    dateComponents.year = 2015

    let certainDate = NSCalendar(identifier: NSCalendarIdentifierGregorian)!.dateFromComponents(dateComponents)!
    let durationDateComponents = NSCalendar(identifier: NSCalendarIdentifierGregorian)!.components( [.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: NSDate(), toDate:certainDay, options: [])

    yearsLabel.text = "\(durationDateComponents.year)"
    monthsLabel.text = "\(durationDateComponents.month)"
    daysLabel.text = "\(durationDateComponents.day)"
}

这段代码在计算从那天起已经过了多少天,但它不会倒计时,这是为什么呢?我如何做到这一点?

【问题讨论】:

  • 如果我将 certainDay 更改为 birthDate 我得到了距离该日期的年数、月数和天数 - 你想要什么?
  • 不,应该是确定的日期。而且它不会显示日期的年、月和日,它会出于某种原因从日期显示它。
  • 我运行了你的代码,得到了 0 年 2 个月 11 天,这对我来说似乎是正确的
  • @Paulw11,我有 18 天 1 小时 2 分钟,它就卡在那里了。完全相同的代码。
  • 这是我操场上的直接复制粘贴 - gist.github.com/paulw11/d6b1be47d3f6bc20eaf6。您的代码没有说明小时、分钟或秒

标签: ios swift swift2


【解决方案1】:

我不完全理解你的问题,但是这个 sn-p 会告诉你我下一个生日之前的日子。 :)

let now = NSDate()
let birthdayDay = 23
let birthdayMonth = 8
let calendar = NSCalendar.currentCalendar()
let thisYear = calendar.component(.Year, fromDate: now)
let bdayComponents = NSDateComponents()
bdayComponents.day = birthdayDay
bdayComponents.month = birthdayMonth
bdayComponents.year = thisYear
var bdayDate = calendar.dateFromComponents(bdayComponents)!
var timeLeft = bdayDate.timeIntervalSinceDate(now)

if (timeLeft < 0) {
    bdayComponents.year = thisYear + 1
    bdayDate = calendar.dateFromComponents(bdayComponents)!
    timeLeft = bdayDate.timeIntervalSinceDate(now)
}

let componentsUntilBday = calendar.components(.Day, fromDate: now, toDate: bdayDate, options: NSCalendarOptions.MatchStrictly)
print("Scott's birthday is in \(componentsUntilBday.day) days!")

更新代码以在 cmets 中使用建议

【讨论】:

  • 嗯,如何在标签上显示?这段代码对我来说不是很清楚。
  • 不应使用此代码。不是每一天都有 84600 秒。
  • @rmaddy 你是对的,我不建议任何人在银行应用程序中使用它,但我认为我们可以让他的生日倒计时应用程序的标准日想法滑动。尽管如此,这是一个幼稚的实现,并且会为我的教育提供更优雅的解决方案。
  • 查看NSCalendar components:fromDate:toDate:options: 方法。
  • @AmitNivedanKalra 将此代码放入 Playground 中,看看我是如何度过生日的。您可以使用类似的东西来更新 UILabel 的文本。如果您希望它连续倒计时,那么您将需要研究如何使用像 NSTimer 这样的计时器在您指定的每个时间间隔调用此代码。
猜你喜欢
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 2023-03-26
  • 2012-06-30
  • 1970-01-01
  • 2020-08-30
相关资源
最近更新 更多