【问题标题】:Calculate seconds between now and an arbitrary time and day in the future [duplicate]计算从现在到未来任意时间和日期之间的秒数[重复]
【发布时间】:2015-03-28 03:40:59
【问题描述】:

如何计算从现在到特定日期和时间(例如下个月 20 日下午 6 点)的时间差(以秒为单位)?

我尝试了很多,但没有经过大量计算和检查很多不同的案例,就没有成功地找到一个简单的解决方案。

NSDate *now = [NSDate date];
NSDateComponents *dc = [[NSDateComponents alloc] init];
[dc setMonth:1];
MyTargetDateObject = [[NSCalendar currentCalendar] dateByAddingComponents:dc  toDate:now options:0];
    [dc release];

..从现在开始增加 1 个月。其他例子例如here 似乎不适用。

【问题讨论】:

  • 日期秒。所以形成两个日期并减去。

标签: objective-c cocoa-touch nsdate nstimeinterval date-arithmetic


【解决方案1】:

类似这样的东西(你必须从 Swift 翻译,但我相信你明白了):

let now = NSDate()
let greg = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let u : NSCalendarUnit = .CalendarUnitYear | .CalendarUnitMonth
var dc = greg!.components(u, fromDate: now)
dc.month += 1 // next month
dc.hour = 18 // at 6 PM
dc.day = 20 // on the 20th
let then = greg!.dateFromComponents(dc)!
let diff = then.timeIntervalSinceNow // time interval = seconds

请注意,我们可以通过添加到 NSDateComponents 的所需单元来进行日期运算。另请注意,所有日期 日期组件转换都需要通过日历。

【讨论】:

    猜你喜欢
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 2016-05-30
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多