简体   繁体   中英

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

and obtain as a result: 1 year, 1 month, 1 week, 2 hours, 4 minutes

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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