如何设置指定日期和时间的变量?

时间:2011-07-04 15:34:33

标签: iphone objective-c xcode

我搜索了很多但是没有找到任何显示如何存储指定时间的实例。例如,我需要在适当的变量中保存代码中15:48的时间(我猜这应该是NSDate对象)。这是必要的,因为我想保留确切的时间来替换下面的方法,而不是现在的时间间隔,而是我确切的指定时间来触发通知。谢谢你的帮助。

NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:5]; 
notification.fireDate  = notificationDate;

3 个答案:

答案 0 :(得分:1)

使用NSDateComponents

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:15];    // 15:48 from your example
[comps setMinute:48];  // 15:48 from your example
/// also set year, month and day
NSCalendar *gregorian = [[NSCalendar alloc]
    initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];

您还可以使用NSDateCompnents从当前日期和时间读取组件 - 因此,如果您想将NSDate设置为今天的15:48,您首先要创建一个NSDate,然后提取日,月和年从它,但覆盖小时和分钟。

答案 1 :(得分:0)

答案 2 :(得分:-1)

相关问题