JAVA将分钟转换为默认时间[hh:mm:ss] [英] JAVA convert minutes into default time [hh:mm:ss]

查看:396
本文介绍了JAVA将分钟转换为默认时间[hh:mm:ss]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将分钟(两倍)转换为默认时间hh:mm:ss

what is the easiest and fastest way to convert minutes (double) to default time hh:mm:ss

的最简单,最快的方法是什么,例如我在python中使用了此代码,

for example I used this code in python and it's working

时间= timedelta(分钟= 250.0)
的打印时间

time = timedelta(minutes=250.0) print time

结果:
4:10:00

result: 4:10:00

有Java库或简单的代码可以做到吗?

is there a java library or a simple code can do it?

推荐答案

编辑:若要将秒显示为SS,您可以使一个简单的自定义格式变量传递给 String.format()方法

EDIT: To show the seconds as SS you can make an easy custom formatter variable to pass to the String.format() method

编辑:添加了添加一分钟并重新计算的逻辑如果初始双精度值的小数点分隔符后的数字值大于59。

EDIT: Added logic to add one minute and recalculate seconds if the initial double value has the number value after the decimal separator greater than 59.

EDIT :在double(喜欢使用doubles!) seconds ,因此时不时地将其作为错误的值。更改了代码以正确计算并四舍五入。还添加了逻辑,以处理由于秒级联而导致分钟和小时溢出的情况。

EDIT: Noticed loss of precision when doing math on the double (joy of working with doubles!) seconds, so every now and again it would not be the correct value. Changed code to properly calculate and round it. Also added logic to treat cases when minutes and hour overflow because of cascading from seconds.

尝试一下(无需外部库)

Try this (no external libraries needed)

public static void main(String[] args) {
    final double t = 1304.00d;

    if (t > 1440.00d) //possible loss of precision again
        return;

    int hours = (int)t / 60;
    int minutes = (int)t % 60;
    BigDecimal secondsPrecision = new BigDecimal((t - Math.floor(t)) * 100).setScale(2, RoundingMode.HALF_UP);
    int seconds = secondsPrecision.intValue();

    boolean nextDay = false;

    if (seconds > 59) {
        minutes++; //increment minutes by one
        seconds = seconds - 60; //recalculate seconds
    }

    if (minutes > 59) {
        hours++;
        minutes = minutes - 60;
    }

    //next day
    if (hours > 23) {
        hours = hours - 24;
        nextDay = true;
    }

    //if seconds >=10 use the same format as before else pad one zero before the seconds
    final String myFormat = seconds >= 10 ? "%d:%02d:%d" : "%d:%02d:0%d";
    final String time = String.format(myFormat, hours, minutes, seconds);
    System.out.print(time);
    System.out.println(" " + (nextDay ? "The next day" : "Current day"));
}

当然,这可以继续进行下去,扩展此算法以将其推广。到目前为止,它的工作将持续到第二天,但不会再进行下去,因此我们可以将初始倍数限制为该值。

Of course this can go on and on, expanding on this algorithm to generalize it. So far it will work until the next day but no further, so we could limit the initial double to that value.

 if (t > 1440.00d)
        return;

这篇关于JAVA将分钟转换为默认时间[hh:mm:ss]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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