开发者

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

开发者 https://www.devze.com 2023-01-31 15:11 出处:网络
How can I know the number of years, months, weeks, days, hours and minutes from a date in the past (fixed开发者_运维百科) to now?

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!


-components:fromDate:toDate:options: method in NSCalendar class does exactly what you need - you can specify what date components you need in your difference setting corresponding flags in the 1st parameter (check reference docs for more details)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号