如何动态更改日期格式

How to change dynamically date format

我有时间问题 format.Some 时间我有 hh:mm:ss 格式的值,有时 mm:ss 格式。

我的代码如下:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String time = "01:48:00"
Date remainedTimeDate = sdf.parse(time);

它有效,当我得到格式 hh:mm:ss 但当我有时间使用格式 mm:ss 时,我得到一个错误,比如无法解析值。是否可以动态更改日期格式?

是的,你可以做到。基于 If 条件,例如,如果 Hour 和 Min 在较小的情况下,您可以更改构造函数。但是请知道简单的日期格式不是线程安全的。使方法同步或锁定简单日期格式对象。

日期时间 API 中没有内置功能可以这样做。此外,遗留日期时间 API(java.util 日期时间类型及其格式 API、SimpleDateFormat)已经过时且容易出错。建议完全停止使用,改用java.timemodern date-time API* .

您可以将字符串与正则表达式模式匹配,\d{1,2}:\d{1,2} 表示用冒号分隔的一个或两个数字。如果匹配成功,将 00: 添加到字符串前,将其转换为 HH:mm:ss 格式。

演示:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] arg) {
        // Test
        Stream.of(
                    "01:48:00", 
                    "48:00"
        ).forEach(s -> parseToTime(s).ifPresent(System.out::println));
    }

    static Optional<LocalTime> parseToTime(String s) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m:s");
        if (s.matches("\d{1,2}:\d{1,2}")) {
            s = "00:" + s;
        }
        LocalTime time = null;
        try {
            time = LocalTime.parse(s, dtf);
        } catch (DateTimeParseException e) {
            System.out.println(s + " could not be parsed into time.");
        }
        return Optional.ofNullable(time);
    }
}

输出:

01:48
00:48

Trail: Date Time.

了解有关现代日期时间的更多信息 API

* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and

java.time.Duration

假设您的字符串表示时间量(例如,持续时间),在 Java 中用于它的权利 class 是 Duration 来自 java.time,现代 Java 日期和时间 API。不幸的是 Duration 无法开箱即用地解析您的字符串。它有一个 parse 方法,只接受 ISO 8601 格式。持续时间的 ISO 8601 格式例如 PT1H48M30S。一开始它看起来很不寻常,但当您知道如何操作时,它就很容易阅读。将刚刚给出的示例阅读为 1 小时 48 分 30 秒的时间段。因此,为了解析 hh:mm:ss 和 mm:ss 格式的字符串,我首先使用几个正则表达式将它们转换为 ISO 8601。

    // Strings can be hh:mm:ss or just mm:ss
    String[] examples = { "01:48:30", "26:57" };
    for (String example : examples) {
        // First try to replace form with two colons, then form with one colon.
        // Exactly one of them should succeed.
        String isoString = example.replaceFirst("^(\d+):(\d+):(\d+)$", "PTHMS")
                .replaceFirst("^(\d+):(\d+)$", "PTMS");
        Duration dur = Duration.parse(isoString);
        System.out.format("%8s -> %-10s -> %7d milliseconds%n", example, dur, dur.toMillis());
    }

此外,我的代码还展示了如何将每个持续时间转换为毫秒。输出为:

01:48:30 -> PT1H48M30S -> 6510000 milliseconds
   26:57 -> PT26M57S   -> 1617000 milliseconds

链接