当一天不等于 24 小时时向 NSDate 添加日期 - iOS
我想向 NSDate 对象添加一天(如果它是过去的一天)(对于闹钟)。然而,如果我只添加 60*60*24 秒,我就会遇到问题。它增加了 24 小时,就像通常想要的那样,但在本例中一天等于 23 小时。我该如何解决这个问题?这是以下代码:
while ([alarmTime compare:[[NSDate alloc] init]] == NSOrderedAscending) {
alarmTime = [alarmTime dateByAddingTimeInterval:(60*60*24)]; //if in the past add a day
NSLog(@"alarm %@ is in the past, adding a day", alarmTime);
}
22:19:59.506: alarm 03/12/2011 12:00:00 AM is in the past, adding a day
22:19:59.506: alarm 03/13/2011 12:00:00 AM is in the past, adding a day
22:19:59.507: alarm 03/14/2011 01:00:00 AM is in the past, adding a day
22:19:59.507: alarm 03/15/2011 01:00:00 AM is in the past, adding a day
I want to add a day to a NSDate object if its in the past (for an Alarm). However I ran into a problem if I just add 60*60*24 seconds. It adds 24 hours like what is usually wanted but in this case a day equals 23 hours. How do I fix this? Here is the following code:
while ([alarmTime compare:[[NSDate alloc] init]] == NSOrderedAscending) {
alarmTime = [alarmTime dateByAddingTimeInterval:(60*60*24)]; //if in the past add a day
NSLog(@"alarm %@ is in the past, adding a day", alarmTime);
}
22:19:59.506: alarm 03/12/2011 12:00:00 AM is in the past, adding a day
22:19:59.506: alarm 03/13/2011 12:00:00 AM is in the past, adding a day
22:19:59.507: alarm 03/14/2011 01:00:00 AM is in the past, adding a day
22:19:59.507: alarm 03/15/2011 01:00:00 AM is in the past, adding a day
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是一个错误,而是 NSDate 的
description
方法如何格式化日志记录的日期。请记住,NSDate 仅存储自参考日期以来的时间间隔,因此添加一天的秒数总是会增加一天。在您所在的时区,夏令时从 3 月 13 日开始,因此前一天午夜后 24 小时为凌晨 1 点。关于您对如何解决此问题的评论,您想解决什么?您问题中的代码将为
alarmTime
添加 24 小时,直到将来的alarmTime
为止。如果您的要求实际上是用户输入,例如上午 5 点,并且您希望alarmTime
为下一个上午 5 点,那么这并不是真正的解决方法,您最好使用NSDateComponents
合成一个新日期。This isn't a bug, it is how NSDate's
description
method formats the date for your logging. Remember, NSDate just stores a time interval since a reference date, so adding a days worth of seconds will always increase it by a day. In your time zone, daylight savings time begins on 13 march, so 24 hours after midnight on the day before is 1 am.Regarding your comment of how to fix this, what do you want to fix? The code in your question will add 24 hours to
alarmTime
untilalarmTime
is in the future. If your requirement is actually that the user enters, say, 5am, and you wantalarmTime
to be the next 5am, then this isn't really the way to go about it, you'd be better off synthesising a new date usingNSDateComponents
.这是我现在使用的解决此问题的代码:
Here is the code I am now using that corrects this issue: