如何将 NSTimeInterval(秒)转换为分钟

发布于 2024-07-29 09:30:56 字数 203 浏览 5 评论 0原文

我得到了某个事件过去的时间。 它存储在 NSTimeInterval 数据类型中。

我想将其转换为分钟

例如,我有:“326.4”秒,我想将其转换为以下字符串: “5:26”。

实现这一目标的最佳方法是什么?

谢谢。

I've got an amount of seconds that passed from a certain event. It's stored in a NSTimeInterval data type.

I want to convert it into minutes and seconds.

For example I have: "326.4" seconds and I want to convert it into the following string:
"5:26".

What is the best way to achieve this goal?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

梦纸 2024-08-05 09:33:27

斯威夫特2版本

extension NSTimeInterval {
            func toMM_SS() -> String {
                let interval = self
                let componentFormatter = NSDateComponentsFormatter()

                componentFormatter.unitsStyle = .Positional
                componentFormatter.zeroFormattingBehavior = .Pad
                componentFormatter.allowedUnits = [.Minute, .Second]
                return componentFormatter.stringFromTimeInterval(interval) ?? ""
            }
        }
    let duration = 326.4.toMM_SS()
    print(duration)    //"5:26"

Swift 2 version

extension NSTimeInterval {
            func toMM_SS() -> String {
                let interval = self
                let componentFormatter = NSDateComponentsFormatter()

                componentFormatter.unitsStyle = .Positional
                componentFormatter.zeroFormattingBehavior = .Pad
                componentFormatter.allowedUnits = [.Minute, .Second]
                return componentFormatter.stringFromTimeInterval(interval) ?? ""
            }
        }
    let duration = 326.4.toMM_SS()
    print(duration)    //"5:26"
日记撕了你也走了 2024-08-05 09:33:13

我是如何在 Swift 中做到这一点的(包括将其显示为“01:23”的字符串格式):

let totalSeconds: Double = someTimeInterval
let minutes = Int(floor(totalSeconds / 60))
let seconds = Int(round(totalSeconds % 60))        
let timeString = String(format: "%02d:%02d", minutes, seconds)
NSLog(timeString)

How I did this in Swift (including the string formatting to show it as "01:23"):

let totalSeconds: Double = someTimeInterval
let minutes = Int(floor(totalSeconds / 60))
let seconds = Int(round(totalSeconds % 60))        
let timeString = String(format: "%02d:%02d", minutes, seconds)
NSLog(timeString)
揽月 2024-08-05 09:33:01

请记住,最初的问题是关于字符串输出,而不是伪代码或单个字符串组件。

我想将其转换为以下字符串:“5:26”

许多答案都缺少国际化问题,并且大多数都手动进行数学计算。 一切都那么 20 世纪......

不要自己做数学(Swift 4)

let timeInterval: TimeInterval = 326.4
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.unitsStyle = .positional
if let formatted = dateComponentsFormatter.string(from: timeInterval) {
    print(formatted)
}

5:26


利用库

如果您确实想要单独的组件和可读性好的代码,请查看 SwiftDate

import SwiftDate
...
if let minutes = Int(timeInterval).seconds.in(.minute) {
    print("\(minutes)")
}

5


感谢 @mickmaccallum@polarwar 充分使用 DateComponentsFormatter

Remember that the original question is about a string output, not pseudo-code or individual string components.

I want to convert it into the following string: "5:26"

Many answers are missing the internationalization issues, and most doing the math computations by hand. All just so 20th century...

Do not do the Math yourself (Swift 4)

let timeInterval: TimeInterval = 326.4
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.unitsStyle = .positional
if let formatted = dateComponentsFormatter.string(from: timeInterval) {
    print(formatted)
}

5:26


Leverage on libraries

If you really want individual components, and pleasantly readable code, check out SwiftDate:

import SwiftDate
...
if let minutes = Int(timeInterval).seconds.in(.minute) {
    print("\(minutes)")
}

5


Credits to @mickmaccallum and @polarwar for adequate usage of DateComponentsFormatter

若水微香 2024-08-05 09:32:49

因为它本质上是一个双精度...

除以 60.0 并提取整数部分和小数部分。

整数部分将是整数分钟。

再次将小数部分乘以 60.0。

结果将是剩余的秒数。

Since it's essentially a double...

Divide by 60.0 and extract the integral part and the fractional part.

The integral part will be the whole number of minutes.

Multiply the fractional part by 60.0 again.

The result will be the remaining seconds.

ˉ厌 2024-08-05 09:32:39
    NSDate *timeLater = [NSDate dateWithTimeIntervalSinceNow:60*90];

    NSTimeInterval duration = [timeLater  timeIntervalSinceNow];

    NSInteger hours = floor(duration/(60*60));
    NSInteger minutes = floor((duration/60) - hours * 60);
    NSInteger seconds = floor(duration - (minutes * 60) - (hours * 60 * 60));

    NSLog(@"timeLater: %@", [dateFormatter stringFromDate:timeLater]);

    NSLog(@"time left: %d hours %d minutes  %d seconds", hours,minutes,seconds);

输出:

timeLater: 22:27
timeLeft: 1 hours 29 minutes  59 seconds
    NSDate *timeLater = [NSDate dateWithTimeIntervalSinceNow:60*90];

    NSTimeInterval duration = [timeLater  timeIntervalSinceNow];

    NSInteger hours = floor(duration/(60*60));
    NSInteger minutes = floor((duration/60) - hours * 60);
    NSInteger seconds = floor(duration - (minutes * 60) - (hours * 60 * 60));

    NSLog(@"timeLater: %@", [dateFormatter stringFromDate:timeLater]);

    NSLog(@"time left: %d hours %d minutes  %d seconds", hours,minutes,seconds);

Outputs:

timeLater: 22:27
timeLeft: 1 hours 29 minutes  59 seconds
末蓝 2024-08-05 09:32:27

这是一个 Swift 版本:

func durationsBySecond(seconds s: Int) -> (days:Int,hours:Int,minutes:Int,seconds:Int) {
    return (s / (24 * 3600),(s % (24 * 3600)) / 3600, s % 3600 / 60, s % 60)
}

可以像这样使用:

let (d,h,m,s) = durationsBySecond(seconds: duration)
println("time left: \(d) days \(h) hours \(m) minutes \(s) seconds")

Here's a Swift version:

func durationsBySecond(seconds s: Int) -> (days:Int,hours:Int,minutes:Int,seconds:Int) {
    return (s / (24 * 3600),(s % (24 * 3600)) / 3600, s % 3600 / 60, s % 60)
}

Can be used like this:

let (d,h,m,s) = durationsBySecond(seconds: duration)
println("time left: \(d) days \(h) hours \(m) minutes \(s) seconds")
通知家属抬走 2024-08-05 09:32:17

Brian Ramsay 的代码,去伪化后:

- (NSString*)formattedStringForDuration:(NSTimeInterval)duration
{
    NSInteger minutes = floor(duration/60);
    NSInteger seconds = round(duration - minutes * 60);
    return [NSString stringWithFormat:@"%d:%02d", minutes, seconds];
}

Brian Ramsay’s code, de-pseudofied:

- (NSString*)formattedStringForDuration:(NSTimeInterval)duration
{
    NSInteger minutes = floor(duration/60);
    NSInteger seconds = round(duration - minutes * 60);
    return [NSString stringWithFormat:@"%d:%02d", minutes, seconds];
}
贩梦商人 2024-08-05 09:32:07

如果您的目标是 iOS 8 或 OS X 10.10 或更高版本,这会变得容易得多。 新的 NSDateComponentsFormatter 类允许您将给定的 NSTimeInterval 从其以秒为单位的值转换为本地化字符串以向用户显示。 例如:

Objective-C

NSTimeInterval interval = 326.4;

NSDateComponentsFormatter *componentFormatter = [[NSDateComponentsFormatter alloc] init];

componentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
componentFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;

NSString *formattedString = [componentFormatter stringFromTimeInterval:interval];
NSLog(@"%@",formattedString); // 5:26

Swift

let interval = 326.4

let componentFormatter = NSDateComponentsFormatter()

componentFormatter.unitsStyle = .Positional
componentFormatter.zeroFormattingBehavior = .DropAll

if let formattedString = componentFormatter.stringFromTimeInterval(interval) {
    print(formattedString) // 5:26
}

NSDateCompnentsFormatter 还允许此输出采用更长的形式。 更多信息可以在 NSHipster 的 NSFormatter 文章中找到。 根据您已经使用的类(如果不是 NSTimeInterval),向格式化程序传递一个 NSDateComponents 实例或两个 可能会更方便NSDate 对象,也可以通过以下方法完成。

Objective-C

NSString *formattedString = [componentFormatter stringFromDate:<#(NSDate *)#> toDate:<#(NSDate *)#>];
NSString *formattedString = [componentFormatter stringFromDateComponents:<#(NSDateComponents *)#>];

Swift

if let formattedString = componentFormatter.stringFromDate(<#T##startDate: NSDate##NSDate#>, toDate: <#T##NSDate#>) {
    // ...
}

if let formattedString = componentFormatter.stringFromDateComponents(<#T##components: NSDateComponents##NSDateComponents#>) {
    // ...
}

If you're targeting at or above iOS 8 or OS X 10.10, this just got a lot easier. The new NSDateComponentsFormatter class allows you to convert a given NSTimeInterval from its value in seconds to a localized string to show the user. For example:

Objective-C

NSTimeInterval interval = 326.4;

NSDateComponentsFormatter *componentFormatter = [[NSDateComponentsFormatter alloc] init];

componentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
componentFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;

NSString *formattedString = [componentFormatter stringFromTimeInterval:interval];
NSLog(@"%@",formattedString); // 5:26

Swift

let interval = 326.4

let componentFormatter = NSDateComponentsFormatter()

componentFormatter.unitsStyle = .Positional
componentFormatter.zeroFormattingBehavior = .DropAll

if let formattedString = componentFormatter.stringFromTimeInterval(interval) {
    print(formattedString) // 5:26
}

NSDateCompnentsFormatter also allows for this output to be in longer forms. More info can be found in NSHipster's NSFormatter article. And depending on what classes you're already working with (if not NSTimeInterval), it may be more convenient to pass the formatter an instance of NSDateComponents, or two NSDate objects, which can be done as well via the following methods.

Objective-C

NSString *formattedString = [componentFormatter stringFromDate:<#(NSDate *)#> toDate:<#(NSDate *)#>];
NSString *formattedString = [componentFormatter stringFromDateComponents:<#(NSDateComponents *)#>];

Swift

if let formattedString = componentFormatter.stringFromDate(<#T##startDate: NSDate##NSDate#>, toDate: <#T##NSDate#>) {
    // ...
}

if let formattedString = componentFormatter.stringFromDateComponents(<#T##components: NSDateComponents##NSDateComponents#>) {
    // ...
}
妞丶爷亲个 2024-08-05 09:31:59

请原谅我是一个 Stack 处女...我不知道如何回复 Brian Ramsay 的答案...

对于 59.5 和 59.99999 之间的第二个值,使用 round 不起作用。 在此期间第二个值将为 60。 使用 trunc 代替...

 double progress;

 int minutes = floor(progress/60);
 int seconds = trunc(progress - minutes * 60);

Forgive me for being a Stack virgin... I'm not sure how to reply to Brian Ramsay's answer...

Using round will not work for second values between 59.5 and 59.99999. The second value will be 60 during this period. Use trunc instead...

 double progress;

 int minutes = floor(progress/60);
 int seconds = trunc(progress - minutes * 60);
水波映月 2024-08-05 09:31:51

所有这些看起来都比实际需要的更复杂! 这是将时间间隔转换为小时、分钟和秒的一种简短而甜蜜的方法:

NSTimeInterval timeInterval = 326.4;
long seconds = lroundf(timeInterval); // Since modulo operator (%) below needs int or long

int hour = seconds / 3600;
int mins = (seconds % 3600) / 60;
int secs = seconds % 60;

请注意,当您将浮点数放入 int 中时,您会自动获得 Floor(),但您可以将其添加到前两个 if if 让您感觉更好的 :-)

All of these look more complicated than they need to be! Here is a short and sweet way to convert a time interval into hours, minutes and seconds:

NSTimeInterval timeInterval = 326.4;
long seconds = lroundf(timeInterval); // Since modulo operator (%) below needs int or long

int hour = seconds / 3600;
int mins = (seconds % 3600) / 60;
int secs = seconds % 60;

Note when you put a float into an int, you get floor() automatically, but you can add it to the first two if if makes you feel better :-)

猫烠⑼条掵仅有一顆心 2024-08-05 09:31:42

伪代码:

minutes = floor(326.4/60)
seconds = round(326.4 - minutes * 60)

pseudo-code:

minutes = floor(326.4/60)
seconds = round(326.4 - minutes * 60)
留一抹残留的笑 2024-08-05 09:31:33

简要说明

  1. 如果您只想转换为分钟,Brian Ramsay 的答案会更方便。
  2. 如果您希望 Cocoa API 为您做这件事,并将您的 NSTimeInterval 不仅转换为分钟,还转换为天、月、周等,...我认为这是一种更通用的方法
  3. 使用 NSCalendar 方法:

    • (NSDateComponents *)组件:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate 选项:(NSUInteger)opts

    • “作为使用指定组件的 NSDateComponents 对象,返回两个提供的日期之间的差异”。 来自 API 文档。

  4. 创建2个NSDate,其差值是要转换的NSTimeInterval。 (如果您的 NSTimeInterval 来自比较 2 个 NSDate,则不需要执行此步骤,甚至不需要 NSTimeInterval)。

  5. 从 NSDateComponents 获取您的报价

示例代码

// The time interval 
NSTimeInterval theTimeInterval = 326.4;

// 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 *conversionInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];

NSLog(@"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);

[date1 release];
[date2 release];

已知问题

  • 对于只是一个转换来说太多了,你是对的,但这就是API 有效。
  • 我的建议:如果您习惯使用 NSDate 和 NSCalendar 管理时间数据,API 将为您完成这项艰苦的工作。

Brief Description

  1. The answer from Brian Ramsay is more convenient if you only want to convert to minutes.
  2. If you want Cocoa API do it for you and convert your NSTimeInterval not only to minutes but also to days, months, week, etc,... I think this is a more generic approach
  3. 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.

  4. Create 2 NSDate whose difference is the NSTimeInterval you want to convert. (If your NSTimeInterval comes from comparing 2 NSDate you don't need to do this step, and you don't even need the NSTimeInterval).

  5. Get your quotes from NSDateComponents

Sample Code

// The time interval 
NSTimeInterval theTimeInterval = 326.4;

// 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 *conversionInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];

NSLog(@"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);

[date1 release];
[date2 release];

Known issues

  • Too much for just a conversion, you are right, but that's how the API works.
  • My suggestion: if you get used to manage your time data using NSDate and NSCalendar, the API will do the hard work for you.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文