将分钟(双倍)转换为默认时间hh:mm:ss的最简单,最快的方法是什么
例如我在python中使用了这段代码,它正在工作
时间= timedelta(分钟= 250.0)打印时间
结果:4:10:00
有没有Java库或简单的代码可以做到这一点?
编辑:以秒为单位显示您可以使一个简单的自定义格式变量传递给该String.format()
方法
编辑:添加了逻辑以增加一分钟并重新计算,seconds
如果初始双精度值在小数点分隔符之后的数字值大于59。
编辑:在double上进行数学运算时发现精度下降(使用double的乐趣!)seconds
,所以时不时地,它不是正确的值。更改了代码以正确计算并四舍五入。还添加了逻辑,以处理由于秒级联而导致分钟和小时溢出的情况。
试试看(不需要外部库)
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"));
}
当然,可以继续进行下去,扩展此算法以将其概括化。到目前为止,它将一直工作到第二天,但不会再继续,因此我们可以将初始double值限制为该值。
if (t > 1440.00d)
return;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句