Xcode 如何计算两个日期之间的月份数

发布于 2024-11-16 22:11:36 字数 255 浏览 6 评论 0原文

我想计算自上次启动应用程序以来的月份数量。

为此,我将 viewdidload 中的当前日期作为字符串保存到 NSUserdefaults 中。

在保存当前日期之前,我必须计算旧(保存)日期和当前日期之间的月份差异。

我是 NSDates 编程新手,有人可以告诉我该怎么做吗?以及如何打印标签中的计数?

希望你明白我的意思,也有人可以帮助我......

问候丹尼斯

I would like to calculate the amount of month since the last time an app has been started.

To do this, I save the current date at viewdidload to NSUserdefaults as String.

Before I save the current date, I have to calculate the difference in month between the old(saved) date and the current date.

I am new in programming with NSDates, can someone tell me how to do this? And how to print the count in a lable?

Hope you understand what I mean and also someone could help me...

regards Dennis

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笙痞 2024-11-23 22:11:36

首选方法是使用 NSCalendar

-(int)differenceInMonthsFrom:(NSDate*)older to:(NSDate*)younger {
  NSCalendar *calendar=[NSCalendar currentCalendar];
  NSDateComponents *components=[calendar components:NSMonthCalendarUnit fromDate:older toDate:younger options:0];
  return [components month];
}

请注意,此函数不检查顺序。从存储的字符串到 NSDate 可能是一个技巧;将日期存储为整数可能更明智?

The preferred way is to use NSCalendar.

-(int)differenceInMonthsFrom:(NSDate*)older to:(NSDate*)younger {
  NSCalendar *calendar=[NSCalendar currentCalendar];
  NSDateComponents *components=[calendar components:NSMonthCalendarUnit fromDate:older toDate:younger options:0];
  return [components month];
}

Note that this function does not check for ordering. Getting from your stored string to NSDate may be a trick; it might be wiser to store the date as an integer?

一片旧的回忆 2024-11-23 22:11:36

您必须使用 NSDate 对象。例如 :

 NSDate *now=[NSDate date];   // this is **now** date object
 NSDate *lastSaved=[NSdate lastDate];   // this is last saved object
 NSComparisonResult duration=[now timeIntervalSinceDate:lastSaved];   //this will return time interval between this 2 date object in seconds
 hoursInterval=duration/3600;  // this will return hours of interval between this 2 date
 daysInterval=hoursInterval/24;  // this will return days interval between this 2 date
 monthsInterval=daysInterval/30;  // and this will return month interval between this 2 date

you have to use NSDate objects. for example :

 NSDate *now=[NSDate date];   // this is **now** date object
 NSDate *lastSaved=[NSdate lastDate];   // this is last saved object
 NSComparisonResult duration=[now timeIntervalSinceDate:lastSaved];   //this will return time interval between this 2 date object in seconds
 hoursInterval=duration/3600;  // this will return hours of interval between this 2 date
 daysInterval=hoursInterval/24;  // this will return days interval between this 2 date
 monthsInterval=daysInterval/30;  // and this will return month interval between this 2 date
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文