本地时间直到那时格式

Localtime until then format

想知道如何使用两种不同的 long 格式化本地时间的输出: 我的目标是用 until 部分格式化长分和长秒

所需输出示例: 9:02 如9分2秒

    public static String getTimeUntilSomething() {
        LocalTime currentTime = LocalTime.now();
        
        long minutes = currentTime.until(currentTimeMore, ChronoUnit.MINUTES);
        long seconds = currentTime.until(currentTimeMore, ChronoUnit.SECONDS);

        String L = currentTime.format(DateTimeFormatter.ofPattern("m:ss"));
        return L;
    }

鉴于您在评论中所说的内容,我认为您可以使用 String.format(),如下所示:

public static String getTimeUntilSomething() {
    LocalTime currentTime = LocalTime.now();
    
    long minutes = currentTime.until(currentTimeMore, ChronoUnit.MINUTES);
    long seconds = currentTime.until(currentTimeMore, ChronoUnit.SECONDS);

    String L = String.format("%d:%02d", minutes % 60, seconds % 60);
    return L;
}

我建议您使用 java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation 来完成。 Java-9 引入了一些更方便的方法。

演示:

import java.time.Duration;
import java.time.LocalTime;

class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getTimeUntilSomething(LocalTime.of(21, 10, 20)));
    }

    public static String getTimeUntilSomething(LocalTime currentTimeMore) {
        LocalTime currentTime = LocalTime.now();
        Duration duration = Duration.between(currentTime, currentTimeMore);

        // ####################################Java-8####################################
        return String.format("%2d:%02d", duration.toMinutes(), duration.toSeconds() % 60);
        // ##############################################################################

        // ####################################Java-9####################################
        // return String.format("%d:%02d", duration.toMinutes(), duration.toSecondsPart());
        // ####################################Java-9####################################
    }
}

样本运行:

94:40