Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 格式化一段时间_Java_Time_Formatting - Fatal编程技术网

Java 格式化一段时间

Java 格式化一段时间,java,time,formatting,Java,Time,Formatting,在Java中,我有一个长整数,以毫秒为单位表示一段时间。时间段可以是几秒钟到几周。我想将这个时间段输出为带有适当单位的字符串 例如,3000应输出为“3秒”,61200000应输出为“17小时”,1814400000应输出为“3周” 理想情况下,我还能够微调子单元的格式,例如,6258000可能输出为“17小时23分钟” 是否有任何现有的Java类可以处理此问题?库可以为您这样做: PeriodFormatter yearsAndMonths = new PeriodFormatterBuild

在Java中,我有一个长整数,以毫秒为单位表示一段时间。时间段可以是几秒钟到几周。我想将这个时间段输出为带有适当单位的字符串

例如,3000应输出为“3秒”,61200000应输出为“17小时”,1814400000应输出为“3周”

理想情况下,我还能够微调子单元的格式,例如,6258000可能输出为“17小时23分钟”

是否有任何现有的Java类可以处理此问题?

库可以为您这样做:

PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
 .printZeroAlways()
 .appendYears()
 .appendSuffix(" year", " years")
 .appendSeparator(" and ")
 .printZeroRarely()
 .appendMonths()
 .appendSuffix(" month", " months")
 .toFormatter();

查看joda time的

另请参见Apache commons中的内容。

这是一种丑陋的方式。
        //Something like this works good too         
        long period = ...;
        StringBuffer sb = new StringBuffer();
        sb.insert(0, String.valueOf(period % MILLISECS_IN_SEC) + "%20milliseconds");
        if (period > MILLISECS_IN_SEC - 1)
            sb.insert(0, String.valueOf(period % MILLISECS_IN_MIN / MILLISECS_IN_SEC) + "%20seconds,%20");
        if (period > MILLISECS_IN_MIN - 1)
            sb.insert(0, String.valueOf(period % MILLISECS_IN_HOUR / MILLISECS_IN_MIN) + "%20minutes,%20");
        if (period > MILLISECS_IN_HOUR - 1)
            sb.insert(0, String.valueOf(period % MILLISECS_IN_DAY / MILLISECS_IN_HOUR) + "%20hours,%20");
        if (period > MILLISECS_IN_DAY - 1)
            sb.insert(0, String.valueOf(period / MILLISECS_IN_DAY) + "%20days,%20");

        return sb.toString();