【问题标题】:how to change date when system hit midnight or user change time manual cocoa如何在系统到达午夜或用户更改时间手动可可时更改日期
【发布时间】:2015-05-26 21:35:23
【问题描述】:

我的 mac os x 日历应用程序有问题。我编写代码及其工作正常,但作为代码的其他部分,我想在系统时间到午夜或用户从系统偏好设置更改系统日期时更改我的应用程序的图标。我的代码是这样获取日期的:

- (int)dayNumber {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *now = [NSDate date];

NSCalendar *calendar = [[NSCalendar alloc]
                        initWithCalendarIdentifier:NSCalendarIdentifierPersian];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"fa_IR"];
[dateFormatter setLocale:dateFormatter.locale];
[dateFormatter setCalendar:calendar];
[dateFormatter setDateFormat:@"d"];
NSString *dayNum = [NSString stringWithFormat:@"%@", [dateFormatter stringFromDate:now]];
int a = [dayNum intValue];

NSLog(@"%i", a);
return a;

}

我正在返回一个 int 值,因为在我的其他部分中,我有一个具有 switch 命令的函数,可以检查这个 int 以更改图标集。

顺便说一句,如果用户在应用程序运行时从系统偏好设置更改日期,然后关闭应用程序并再次运行应用程序,应用程序工作正常并检测当前日期。

如何检测系统或用户是否更改日期,以便我也可以更改我的应用日期。

【问题讨论】:

  • 您需要查看有关日历计算的 WWDC 视频。将午夜作为参考点确实存在潜在问题。

标签: objective-c macos cocoa nsdate nsdateformatter


【解决方案1】:

当系统时钟发生变化时,系统会发布通知NSSystemClockDidChangeNotification,您可以使用NSNotficationCenter观察。

要知道日期何时因时间流逝而改变,您可以使用计时器。将计时器的触发日期计算为第二天的开始:

NSDateComponents* dayComponents = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit
                                              fromDate:[NSDate date]];
dayComponents.day++;
NSDate* startOfTomorrow = [calendar dateFromComponents:components];

【讨论】:

  • 感谢您的帮助,但您能否更具体一些,我是 Objective-c 的新手。我不明白你对 nsdatecomponent 的看法。好的,我实现了 nsdatecomponent 但我的日历标识符与其他日历不同,我现在应该如何告诉我的应用程序是用户更改日期还是不更改系统时间或系统时间到午夜。如果你能给我写代码,我很感激
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 2021-10-04
  • 1970-01-01
  • 2012-10-07
  • 2015-12-08
  • 2012-03-31
  • 1970-01-01
相关资源
最近更新 更多