入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

iOS 把NSTimeInterval 转换成年月日 时分秒

创建时间:2011-07-21 投稿人: 浏览次数:4392
    Just another approach to complete the answer of JBRWilkinson but adding some code. It can also offers a solution to Alex Reynolds"s comment.

    Use NSCalendar method:

        (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts

        "Returns, as an NSDateComponents object using specified components, the difference between two supplied dates". (From the API documentation).

    Create 2 NSDate whose difference is the NSTimeInterval you want to break down. (If your NSTimeInterval comes from comparing 2 NSDate you don"t need to do this step, and you don"t even need the NSTimeInterval, just apply the dates to the NSCalendar method).

    Get your quotes from NSDateComponents

Sample Code

// The time interval
NSTimeInterval theTimeInterval = ...;

// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];

// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];

// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];

NSLog(@"Break down: %dmin %dhours %ddays %dmoths",[breakdownInfo minute], [breakdownInfo hour], [breakdownInfo day], [breakdownInfo month]);

[date1 release];
[date2 release];


声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像