将秒格式化为hh:ii:ss [英] Formatting seconds into hh:ii:ss

查看:107
本文介绍了将秒格式化为hh:ii:ss的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本计时器的应用程序.它跟踪应用程序已运行的秒数.我想将其转换为秒(NSUInteger),如下所示:00:00:12(hh:mm:ss).所以我读了这篇文章:

NS秒数到小时,分钟,秒

我从中编写这段代码的地方:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[self meeting] elapsedSeconds]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm:ss"];

它可以正常工作,但从04:00:00开始.我不知道为什么.我也尝试做类似的事情:

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:[[self meeting] elapsedSeconds] * -1];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm:ss"];

认为它会正确显示计数器,但是它会产生一个奇怪的01:23:00,然后翻到04:00:00,并在其余时间停留在那里.

MS

解决方案

这类似于

I have app that is a basic timer. It tracks the number of seconds the app has run. I want to convert it so the seconds (NSUInteger) are displayed like: 00:00:12 (hh:mm:ss). So I've read this post:

NSNumber of seconds to Hours, minutes, seconds

From which I wrote this code:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[self meeting] elapsedSeconds]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm:ss"];

It works fine, but it starts out with 04:00:00. I'm not sure why. I also tried doing something like:

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:[[self meeting] elapsedSeconds] * -1];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm:ss"];

Thinking that it would display the counter correctly, but it does a wierd 01:23:00, then just flops to 04:00:00 and stays there for the rest of the time.

MS

解决方案

This is similar to a previous answer about formatting time but doesn't require a date formatter because we aren't dealing with dates any more.

If you have the number of seconds stored as an integer, you can work out the individual time components yourself:

NSUInteger h = elapsedSeconds / 3600;
NSUInteger m = (elapsedSeconds / 60) % 60;
NSUInteger s = elapsedSeconds % 60;

NSString *formattedTime = [NSString stringWithFormat:@"%u:%02u:%02u", h, m, s];

这篇关于将秒格式化为hh:ii:ss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆