fis*_*ish 42
在这种情况下,您只需要划分.
days = num_seconds / (60 * 60 * 24);
num_seconds -= days * (60 * 60 * 24);
hours = num_seconds / (60 * 60);
num_seconds -= hours * (60 * 60);
minutes = num_seconds / 60;
Run Code Online (Sandbox Code Playgroud)
对于更复杂的日期计算,例如1983年1月19日下午3点后的一千万秒内的天数,您将使用NSCalendar类和NSDateComponents.Apple的日期和时间编程指南可以帮助您.
Amr*_*sal 35
试试这个,
int forHours = seconds / 3600,
remainder = seconds % 3600,
forMinutes = remainder / 60,
forSeconds = remainder % 60;
Run Code Online (Sandbox Code Playgroud)
您可以按照相同的步骤使用它来获取更多详细信息,如天,周,月和年
小智 9
我知道这是一个老帖子,但无论如何我想分享.我使用的是以下代码.
int seconds = (totalSeconds % 60);
int minutes = (totalSeconds % 3600) / 60;
int hours = (totalSeconds % 86400) / 3600;
int days = (totalSeconds % (86400 * 30)) / 86400;
Run Code Online (Sandbox Code Playgroud)
第一行 - 我们得到剩余的秒数除以一分钟内的秒数.
第二行 - 我们在除以一小时内的秒数后得到剩余的秒数.然后我们在一分钟内将它除以秒.
第三行 - 我们在除以一天中的秒数后得到剩余的秒数.然后我们将它除以一小时内的秒数.
第四行 - 我们在除以一个月内的秒数后得到第二行的剩余部分.然后我们将它除以一天中的秒数.我们可以使用以下几天...
int days = totalSeconds / 86400;
Run Code Online (Sandbox Code Playgroud)
但是,如果我们使用上述线路并希望继续使用并获得数月,那么我们最终需要1个月30天才能获得1个月的时间.
在Xcode中打开一个Playground并试一试.
小智 6
Objective-c中最首选的方式可能是这个,正如Apple在他们的文档中所推荐的那样.
NSDate *startDate = [NSDate date];
NSDate *endDate = [NSDate dateWithTimeInterval:(365*24*60*60*3+24*60*60*129) sinceDate:startDate];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger years = [components year];
NSInteger months = [components month];
NSInteger days = [components day];
NSLog(@"years = %ld months = %ld days = %ld",years,months,days);
Run Code Online (Sandbox Code Playgroud)
确保不检索未使用unitFlags定义的组件,整数将是"未定义".
| 归档时间: |
|
| 查看次数: |
61607 次 |
| 最近记录: |