String.format在处理大于一小时的大小时未能提供正确的格式。

huangapple go评论83阅读模式
英文:

String.format does not deliver the correct format for sizes larger than one hour

问题

我想将 3600000 毫秒转换为 01:00:00 格式(表示 01 小时:00 分钟:00 秒)。不幸的是,它给我返回 2: 120: 00。在 60,000 毫秒时,它给我返回 00:10:00,这是正确的结果。但在 00:59:00 之后,他不再以正确的格式输出。

public static String formattedTime(long time) {
    int hours = (int) (time / 1000) / 60 / 60;
    int minutes = (int) (time / 1000) / 60;
    int seconds = (int) (time / 1000) % 60;
    return String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds);
}
英文:

I would like to convert 3600000 milliseconds to the 01:00:00 format (means 01 hours: 00 minutes: 00 seconds). Unfortunately it gives me 2: 120: 00. At 60,000 milliseconds, he gives me 00:10:00, which is the correct result. Until 00:59:00 he outputs the numbers formatted, but everything larger than an hour no longer outputs it in the correct format

public static String formattedTime(long time) {
    int hours = (int) (time / 1000) / 60 / 60;
    int minutes = (int) (time / 1000) / 60;
    int seconds = (int) (time / 1000) % 60;
    return String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds);

}

答案1

得分: 0

按以下方式操作:

import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // 测试
        System.out.println(formattedTime(3600000));
        System.out.println(formattedTime(4580000));
    }

    public static String formattedTime(long time) {
        // 将毫秒转换为秒
        int milliToSec = (int) (time / 1000);

        // 从总秒数中获取小时
        int hours = milliToSec / 3600;

        // 从总秒数中获取分钟
        int minutes = (milliToSec / 60) % 60;

        // 从总秒数中获取剩余的秒数
        int seconds = milliToSec % 60;

        // 返回格式化的字符串
        return String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds);
    }
}

输出:

01:00:00
01:16:20
英文:

Do it as follows:

import java.util.Locale;

public class Main {
	public static void main(String[] args) {
        // Tests
		System.out.println(formattedTime(3600000));
		System.out.println(formattedTime(4580000));
	}

	public static String formattedTime(long time) {
		// Convert time in milliseconds to seconds
		int milliToSec = (int) (time / 1000);

		// Get hours from total seconds
		int hours = milliToSec / 3600;

		// Get minutes from total seconds
		int minutes = (milliToSec / 60) % 60;

		// Get remaining seconds from total seconds
		int seconds = milliToSec % 60;

		// Return formatted string
		return String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds);
	}
}

Output:

01:00:00
01:16:20

huangapple
  • 本文由 发表于 2020年8月5日 00:20:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63251060.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定