objective-c 在 Obj-c 中将秒转换为天、分钟和小时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/572049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert seconds to days, minutes, and hours in Obj-c
提问by higginbotham
In objective-c, how can I convert an integer (representing seconds) to days, minutes, an hours?
在objective-c 中,如何将整数(代表秒)转换为天、分钟、小时?
Thanks!
谢谢!
回答by fish
In this case, you simply need to divide.
在这种情况下,您只需要进行划分。
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;
For more sophisticated date calculations, such as the number of days within the ten million seconds after 3pm on January 19th in 1983, you would use the NSCalendar class along with NSDateComponents. Apple's date and time programming guide helps you here.
对于更复杂的日期计算,例如 1983 年 1 月 19 日下午 3 点之后一千万秒内的天数,您可以将 NSCalendar 类与 NSDateComponents 一起使用。Apple 的日期和时间编程指南可以帮助您。
回答by Amr Faisal
try this,
尝试这个,
int forHours = seconds / 3600,
remainder = seconds % 3600,
forMinutes = remainder / 60,
forSeconds = remainder % 60;
and you can use it to get more details as days, weeks, months, and years by following the same procedure
并且您可以按照相同的程序使用它来获取更多详细信息,如天、周、月和年
回答by Sean Marraffa
I know this is an old post but I wanted to share anyway. The following code is what I use.
我知道这是一个旧帖子,但我还是想分享。以下代码是我使用的。
int seconds = (totalSeconds % 60);
int minutes = (totalSeconds % 3600) / 60;
int hours = (totalSeconds % 86400) / 3600;
int days = (totalSeconds % (86400 * 30)) / 86400;
First line - We get the remainder of seconds when dividing by number of seconds in a minutes.
第一行 - 除以一分钟内的秒数时,我们得到剩余的秒数。
Second line - We get the remainder of seconds after dividing by the number of seconds in an hour. Then we divide that by seconds in a minute.
第二行 - 我们得到除以一小时内的秒数后的剩余秒数。然后我们在一分钟内除以秒。
Third line - We get the remainder of seconds after dividing by the number of seconds in a day. Then we divide that by the number of seconds in a hour.
第三行 - 我们得到除以一天中的秒数后的剩余秒数。然后我们将其除以一小时内的秒数。
Fourth line - We get the remainder of second after dividing by the number of seconds in a month. Then we divide that by the number of seconds in a day. We could just use the following for Days...
第四行 - 除以一个月的秒数后,我们得到秒的余数。然后我们将其除以一天中的秒数。我们可以只使用以下几天...
int days = totalSeconds / 86400;
But if we used the above line and wanted to continue on and get months we would end up with 1 month and 30 days when we wanted to get just 1 month.
但是,如果我们使用上面的行并希望继续并获得几个月,那么当我们只想获得 1 个月时,我们最终会得到 1 个月零 30 天。
Open up a Playground in Xcode and try it out.
在 Xcode 中打开一个 Playground 并尝试一下。
回答by JeanNicolas
The most preferred way in objective-c might be this one, as recommend by Apple in their doc.
正如 Apple 在他们的文档中所推荐的那样,objective-c 中最受青睐的方式可能是这种方式。
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);
Make sure not to retrieve components not defined with the unitFlags, integer will be "undefined".
确保不要检索未使用 unitFlags 定义的组件,整数将为“未定义”。
回答by Craig Detrick
Use the built-in function strftime():
使用内置函数 strftime():
static char timestr[80];
char * HHMMSS ( time_t secs )
{
struct tm ts;
ts = *localtime(&secs);
strftime(timestr, sizeof(timestr), "%a %b %d %H:%M:%S %Y %Z", &ts); // "Mon May 1, 2012 hh:mm:ss zzz"
return timestr;
}
回答by Tai Le Anh
Just a bit modification for both compatible with 32 bit & 64 bit. Using NSIntegerthe system will automatically convert to int or long basing on 32/64 bit.
只需稍微修改即可兼容 32 位和 64 位。使用NSInteger系统会根据32/64位自动转换为int或long。
NSInteger seconds = 10000;
NSInteger remainder = seconds % 3600;
NSInteger hours = seconds / 3600;
NSInteger minutes = remainder / 60;
NSInteger forSeconds = remainder % 60;
By the same way you can convert to days, weeks, months, years
以同样的方式,您可以转换为天、周、月、年
回答by Tor Ymer Nordstr?m
This is my algorithm for converting seconds to seconds, minutes and hours (only using the total amount of seconds and the relation between each of them):
这是我将秒转换为秒、分钟和小时的算法(仅使用秒的总量以及它们之间的关系):
int S = totalSeconds % BaseSMH
int M = ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2) / BaseSMH
int H = (totalSeconds - totalSeconds % BaseSMH - ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2)) / BaseSMH ^ 2
And here follows my explanation of it:
下面是我对它的解释:
Test time converted to seconds: HH:MM:SS = 02:20:10 => totalSeconds = 2 * 3600 + 20 * 60 + 10 = 7200 + 1200 + 10 = 8410
测试时间转换为秒:HH:MM:SS = 02:20:10 => totalSeconds = 2 * 3600 + 20 * 60 + 10 = 7200 + 1200 + 10 = 8410
The base between seconds -> minutes and minutes -> hours is 60 (from seconds -> hours it's 60 ^ 2 = 3600).
秒 -> 分钟和分钟 -> 小时之间的基数是 60(从秒 -> 小时是 60 ^ 2 = 3600)。
int totalSeconds = 8410
const int BaseSMH = 60
Each unit (here represented by a variable) can be calculated by removing the previous unit (expressed in seconds) from the total amount of seconds and divide it by its relation between seconds and the unit we are trying to calculate. This is what each calulation looks like using this algorithm:
每个单位(这里由一个变量表示)可以通过从总秒数中去除前一个单位(以秒表示)并将其除以秒和我们试图计算的单位之间的关系来计算。这是使用此算法进行的每个计算的样子:
int S = totalSeconds % BaseSMH
int M = ((totalSeconds - S) % BaseSMH ^ 2) / BaseSMH
int H = (totalSeconds - S - M * BaseSMH) / BaseSMH ^ 2
As with all math we can now substitute each unit in the minutes and hours calculations with how we calculated the previous unit and each calculation will then look like this (remember that dividing with BaseSMH in the M calculation and multiplying by BaseSMH in the H calulation cancels each other out):
与所有数学一样,我们现在可以将分钟和小时计算中的每个单位替换为我们计算前一个单位的方式,然后每个计算将如下所示(请记住,在 M 计算中除以 BaseSMH 并在 H 计算中乘以 BaseSMH 取消互相出来):
int S = totalSeconds % BaseSMH
int M = ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2) / BaseSMH
int H = (totalSeconds - totalSeconds % BaseSMH - ((totalSeconds - totalSeconds % BaseSMH) % BaseSMH ^ 2)) / BaseSMH ^ 2
Testing with the "totalSeconds" and "BaseSMH" from above will look like this:
使用上面的“totalSeconds”和“BaseSMH”进行测试将如下所示:
int S = 8410 % 60
int M = ((8410 - 8410 % 60) % 60 ^ 2) / 60
int H = (8410 - 8410 % 60 - ((8410 - 8410 % 60) % 60 ^ 2)) / 60 ^ 2
Calculating S:
计算 S:
int S = 8410 % 60 = 10
Calculating M:
计算 M:
int M = ((8410 - 8410 % 60) % 60 ^ 2) / 60
= ((8410 - 10) % 3600) / 60
= (8400 % 3600) / 60
= 1200 / 60
= 20
Calculating H:
计算 H:
int H = (8410 - 8410 % 60 - ((8410 - 8410 % 60) % 60 ^ 2)) / 60 ^ 2
= (8410 - 10 - ((8410 - 10) % 3600)) / 3600
= (8400 - (8400 % 3600)) / 3600
= (8400 - 1200) / 3600
= 7200 / 3600
= 2
With this you can add whichever unit you want, you just need to calculate what the relation is between seconds and the unit you want. Hope you understand my explanations of each step. If not, just ask and I can explain further.
有了这个,你可以添加任何你想要的单位,你只需要计算秒和你想要的单位之间的关系。希望你能理解我对每一步的解释。如果没有,请询问,我可以进一步解释。
回答by timothyzhang
Initially I worked out a solution similar to fish's answer:
最初我想出了一个类似于鱼的答案的解决方案:
const secondsToString = s => {
const secondsOfYear = 60 * 60 * 24 * 365;
const secondsOfDay = 60 * 60 * 24;
const secondsOfHour = 60 * 60;
const secondsOfMinute = 60;
let y = ~~(s / secondsOfYear); s %= secondsOfYear;
let d = ~~(s / secondsOfDay); s %= secondsOfDay;
let h = ~~(s / secondsOfHour); s %= secondsOfHour;
let m = ~~(s / secondsOfMinute); s %= secondsOfMinute;
y = (y > 0 ? (y + 'y ') : '');
d = (d > 0 ? (d + 'd ') : '');
h = (h > 0 ? (h + 'h ') : '');
m = (m > 0 ? (m + 'm ') : '');
s = (s > 0 ? (s + 's ') : '');
return y + d + h + m + s;
}
I noticed that it could be generalized with array map()and reduce()functions since it includes some iterations and recursions.
我注意到它可以用数组map()和reduce()函数进行泛化,因为它包含一些迭代和递归。
const intervalToLevels = (interval, levels) => {
const cbFun = (d, c) => {
let bb = d[1] % c[0],
aa = (d[1] - bb) / c[0];
aa = aa > 0 ? aa + c[1] : '';
return [d[0] + aa, bb];
};
let rslt = levels.scale.map((d, i, a) => a.slice(i).reduce((d, c) => d * c))
.map((d, i) => ([d, levels.units[i]]))
.reduce(cbFun, ['', interval]);
return rslt[0];
};
const TimeLevels = {
scale: [365, 24, 60, 60, 1],
units: ['y ', 'd ', 'h ', 'm ', 's ']
};
const secondsToString = interval => intervalToLevels(interval, TimeLevels);
Easily you could extend the function intervalToLevels()to other measurement levels, such as liquid mass, length, and so on.
您可以轻松地将该功能扩展intervalToLevels()到其他测量级别,例如液体质量、长度等。
const LengthLevels = {
scale: [1760, 3, 12, 1],
units: ['mi ', 'yd ', 'ft ', 'in ']
};
const inchesToString = interval => intervalToLevels(interval, LengthLevels);
const LiquidsLevels = {
scale: [4, 2, 2, 8, 1],
units: ['gal ', 'qt ', 'pt ', 'cup ', 'fl_oz ']
};
const ouncesToString = interval => intervalToLevels(interval, LiquidsLevels);
回答by Deepak Nair
You will get days,hours,minutes and seconds from total seconds(self.secondsLeft)
您将从总秒数(self.secondsLeft)中获得天数、小时数、分钟数和秒数
days = self.secondsLeft/86400;
hours = (self.secondsLeft %86400)/3600;
minutes = (self.secondsLeft % 3600) / 60;
seconds = (self.secondsLeft %3600) % 60;
Code ......
代码 ......
[NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
-(void) updateCountdown {
int days,hours,minutes,seconds;
self.secondsLeft--;
days = self.secondsLeft/86400;
hours = (self.secondsLeft %86400)/3600;
minutes = (self.secondsLeft % 3600) / 60;
seconds = (self.secondsLeft %3600) % 60;
NSLog(@"Time Remaining =%@",[NSString stringWithFormat:@"%02d:%02d:%02d:%02d",days, hours, minutes,seconds]);
}
回答by Vela
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date dateObj1=null;
Date dateObj2=null;
try {
// String format = "MM/dd/yyyy hh:mm:ss";
dateObj1 = sdf.parse(Appconstant.One_One_time);
dateObj2 = sdf.parse(Appconstant.One_Two_time);
Log.e(TAG, "dateObj12" + dateObj1.toString() + "---" + dateObj2.toString());
DecimalFormat crunchifyFormatter = new DecimalFormat("###,###");
long diff = dateObj2.getTime() - dateObj1.getTime();
/*int diffDays = (int) (diff / (24 * 60 * 60 * 1000));
System.out.println("difference between days: " + diffDays);
int diffhours = (int) (diff / (60 * 60 * 1000));
System.out.println("difference between hours: "
+ crunchifyFormatter.format(diffhours));
int diffmin = (int) (diff / (60 * 1000));
System.out.println("difference between minutes: "
+ crunchifyFormatter.format(diffmin));*/
int diffsec = (int) (diff / (1000));
System.out.println("difference between seconds:"
+ crunchifyFormatter.format(diffsec));

