Swift - 将毫秒转换为分钟,秒和毫秒

时间:2015-06-11 04:51:19

标签: swift time nsdate

我正在编写一个赛车应用程序,并希望将大量的毫秒转换为分钟:seconds.milliseconds(例如,$(function () { str_src = $('img').data('src'); console.log(str_src); var source = $('img').attr('data-src'); console.log(source); if (source) { setTimeout(function(){ $('img').attr("src", source); },2000); }; }); )。目前我只是通过数学(1:32.361)来做,然后得到余数并进一步划分,等等,但我发现它偶尔会消失1毫秒。我知道这可能听起来不是什么大不了的事,但我试图找到minutes / 600001:32.004的平均值,并返回1:32.004,这意味着它被错误地放入,其余的该应用无法处理它。

有没有办法使用1:32.003NSDate或类似的东西来将毫秒格式化为MM:ss.mmm?

我查看过这些来源但未找到答案:

How to convert milliseconds into minutes?
Convert seconds into minutes and seconds
Convert milliseconds to minutes
http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/

1 个答案:

答案 0 :(得分:20)

您可以创建一个TimeInterval扩展名来格式化您的已用时间,如下所示:

Xcode 8.3.3•Swift 3.1

public static double[] secondDerivative(Point... P) {
    int n = P.length;
    double yp1=0.0; 
    double ypn=0.0;

    // build the tridiagonal system 
    // (assume 0 boundary conditions: y2[0]=y2[-1]=0) 
    double[][] matrix = new double[n][3];
    double[] result = new double[n];
    matrix[0][1]=1;
    for(int i=1;i<n-1;i++) {
        matrix[i][0]=(double)(P[i].x-P[i-1].x)/6;
        matrix[i][1]=(double)(P[i+1].x-P[i-1].x)/3;
        matrix[i][2]=(double)(P[i+1].x-P[i].x)/6;
        result[i]=(double)(P[i+1].y-P[i].y)/(P[i+1].x-P[i].x) - (double)(P[i].y-P[i-1].y)/(P[i].x-P[i-1].x);
    }
    matrix[n-1][1]=1;

    // solving pass1 (up->down)
    for(int i=1;i<n;i++) {
        double k = matrix[i][0]/matrix[i-1][1];
        matrix[i][1] -= k*matrix[i-1][2];
        matrix[i][0] = 0;
        result[i] -= k*result[i-1];
    }
    // solving pass2 (down->up)
    for(int i=n-2;i>=0;i--) {
        double k = matrix[i][2]/matrix[i+1][1];
        matrix[i][1] -= k*matrix[i+1][0];
        matrix[i][2] = 0;
        result[i] -= k*result[i+1];
    }

    // return second derivative value for each point P
    double[] y2 = new double[n];
    for(int i=0;i<n;i++) y2[i]=result[i]/matrix[i][1];
    return y2;
}
extension TimeInterval {
    var minuteSecondMS: String {
        return String(format:"%d:%02d.%03d", minute, second, millisecond)
    }
    var minute: Int {
        return Int((self/60).truncatingRemainder(dividingBy: 60))
    }
    var second: Int {
        return Int(truncatingRemainder(dividingBy: 60))
    }
    var millisecond: Int {
        return Int((self*1000).truncatingRemainder(dividingBy: 1000))
    }
}

extension Int {
    var msToSeconds: Double {
        return Double(self) / 1000
    }
}