简体   繁体   English

比较两个日期并获得年,月,日的差

[英]Compare two dates and get the difference in years, months, days

How can I know the number of years, months, weeks, days, hours and minutes from a date in the past (fixed) to now? 我如何知道从过去(固定)日期到现在的年,月,周,天,小时和分钟的数量?

For example I want to compare: date1: 2009/11/10 8:23 date2: 2010/12/17 10:27 例如,我想比较:date1:​​2009/11/10 8:23 date2:2010/12/17 10:27

and obtain as a result: 1 year, 1 month, 1 week, 2 hours, 4 minutes 并获得以下结果:1年,1个月,1周,2小时,4分钟

Many thanks! 非常感谢!

NSCalendar类中的NSCalendar -components:fromDate:toDate:options:方法完全满足您的需要-您可以在差异设置中指定第1个参数中的相应标志所需的日期组件(有关更多详细信息,请参见参考文档)

NSDate *today = [NSDate date];
NSTimeInterval interval = [today timeIntervalSinceDate:lastDate];
        int weeksForLastDate=interval/604800;

this gives you weeks similerly you can find years etc. so you need to implement this logic according to you and also date format according to you. 这样您就可以周到地找到年份等。因此,您需要根据自己实现此逻辑,并根据自己实现日期格式。

here interval gives you time in seconds so convert it according to you. 在此间隔时间以秒为单位,因此请根据您的时间进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM