Java 日期格式允许 - / 或 .作为日期内的分隔符

发布于 2024-08-05 07:02:32 字数 176 浏览 10 评论 0 原文

解析可以采用以下格式之一的日期的最好方法是什么,而

 "dd-MM-yyyy HH:mm"
 "dd/MM/yyyy HH:mm"
 "dd.MM.yyyy HH:mm"

无需创建 3 个 SimpleDateFormat 并针对每个格式进行解析。

谢谢

What's the nicest way to parse a date that can be in one of the following formats

 "dd-MM-yyyy HH:mm"
 "dd/MM/yyyy HH:mm"
 "dd.MM.yyyy HH:mm"

without creating 3 SimpleDateFormats and parsing against each one.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

夏有森光若流苏 2024-08-12 07:02:32

将源字符串“调整”为规范格式可能是最简单的:

if (text.length() == 16)
{
    if ((text.charAt(2) == '/' && text.charAt(5) == '/') ||
        (text.charAt(2) == '.' && text.charAt(5) == '.'))
    {
        text = text.substring(0, 2) + "-" + text.substring(3, 5) 
           + "-" + text.substring(6);
    }
}

然后使用“-”来使用格式字符串。

请注意,这是非常具体的,仅完全替换您感兴趣的字符,以避免不必要的副作用。

It's probably easiest to "tweak" the source string into a canonical format:

if (text.length() == 16)
{
    if ((text.charAt(2) == '/' && text.charAt(5) == '/') ||
        (text.charAt(2) == '.' && text.charAt(5) == '.'))
    {
        text = text.substring(0, 2) + "-" + text.substring(3, 5) 
           + "-" + text.substring(6);
    }
}

Then use the format string using "-".

Note that this is very specific, only replacing exactly the characters you're interested in, to avoid unwanted side-effects.

揪着可爱 2024-08-12 07:02:32

您能否先运行两个替换操作,以便将所有三种格式减少为单一格式?

Could you run two replace operations first, so that you reduce all three formats to a single one?

-残月青衣踏尘吟 2024-08-12 07:02:32

您可以使用 Apache commons lang DateUtils.parseDate

import java.text.ParseException;
import org.apache.commons.lang.time.DateUtils;

public class Test {

public static void main(String[] args) throws ParseException {

    String[] values = new String[]{"31-12-2009 12:00", "31/12/2009 12:00", "31.12.2009 12:00"};
    String[] parsePatterns = new String[]{"dd-MM-yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd.MM.yyyy HH:mm"};

    for (String value : values) {
        System.out.println(DateUtils.parseDate(value, parsePatterns));
    }
}
}

好吧,它在内部创建了 SimpleDateFormats,但这有什么问题吗?

You may use Apache commons lang DateUtils.parseDate

import java.text.ParseException;
import org.apache.commons.lang.time.DateUtils;

public class Test {

public static void main(String[] args) throws ParseException {

    String[] values = new String[]{"31-12-2009 12:00", "31/12/2009 12:00", "31.12.2009 12:00"};
    String[] parsePatterns = new String[]{"dd-MM-yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd.MM.yyyy HH:mm"};

    for (String value : values) {
        System.out.println(DateUtils.parseDate(value, parsePatterns));
    }
}
}

Well, internally it creates SimpleDateFormats, but whats wrong with that?

沫离伤花 2024-08-12 07:02:32

java.time

您可以使用 DateTimeFormatter 它允许您使用方括号指定可选的内容。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;

public class Main {
    public static void main(String args[]) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d[-][.][/]M[-][.][/]u H:m", Locale.ENGLISH);

        // Test
        Stream.of(
                    "28-04-2021 14:01", 
                    "28.04.2021 14:01", 
                    "28/04/2021 14:01"
        ).forEach(s -> System.out.println(LocalDateTime.parse(s, dtf)));
    }
}

输出:

2021-04-28T14:01
2021-04-28T14:01
2021-04-28T14:01

跟踪:日期时间

请注意,旧版日期时间 API(java.util 日期时间类型及其格式化 API SimpleDateFormat)已过时且容易出错。建议完全停止使用它们并切换到 java.time,即 现代日期时间 API*


* 无论出于何种原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport 将大部分 java.time 功能向后移植到 Java 6 和 Java 6 7. 如果您正在处理 Android 项目,并且您的 Android API 级别仍然不符合 Java-8,请检查 通过脱糖提供 Java 8+ API如何在Android项目中使用ThreeTenABP

java.time

You can do it using DateTimeFormatter which allows you to specify optional things using square brackets.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;

public class Main {
    public static void main(String args[]) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d[-][.][/]M[-][.][/]u H:m", Locale.ENGLISH);

        // Test
        Stream.of(
                    "28-04-2021 14:01", 
                    "28.04.2021 14:01", 
                    "28/04/2021 14:01"
        ).forEach(s -> System.out.println(LocalDateTime.parse(s, dtf)));
    }
}

Output:

2021-04-28T14:01
2021-04-28T14:01
2021-04-28T14:01

Learn more about the modern date-time API from Trail: Date Time.

Note that the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API* .


* For any reason, if you have to stick to Java 6 or Java 7, you can use 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 How to use ThreeTenABP in Android Project.

提笔书几行 2024-08-12 07:02:32

正则表达式怎么样:

"\\d\\d[./-]\\d\\d[./-]\\d\\d\\d\\d \\d\\d:\\d\\d"

在代码中,这意味着这样的事情:

Pattern pattern = 
Pattern.compile("(\\d\\d)([./-])(\\d\\d)([./-])(\\d\\d\\d\\d) (\\d\\d):(\\d\\d)");

Matcher matcher = 
pattern.matcher("31-07-1983 15:30");

if (matcher.find() && matcher.group(2).equals(matcher.group(4))) {
  int day = Integer.parseInt(matcher.group(1));
  int month = Integer.parseInt(matcher.group(3));
  int year = Integer.parseInt(matcher.group(5));
  int hour = Integer.parseInt(matcher.group(6));
  int minute = Integer.parseInt(matcher.group(7));
} 

how about a regex:

"\\d\\d[./-]\\d\\d[./-]\\d\\d\\d\\d \\d\\d:\\d\\d"

In code this would mean something like this:

Pattern pattern = 
Pattern.compile("(\\d\\d)([./-])(\\d\\d)([./-])(\\d\\d\\d\\d) (\\d\\d):(\\d\\d)");

Matcher matcher = 
pattern.matcher("31-07-1983 15:30");

if (matcher.find() && matcher.group(2).equals(matcher.group(4))) {
  int day = Integer.parseInt(matcher.group(1));
  int month = Integer.parseInt(matcher.group(3));
  int year = Integer.parseInt(matcher.group(5));
  int hour = Integer.parseInt(matcher.group(6));
  int minute = Integer.parseInt(matcher.group(7));
} 
—━☆沉默づ 2024-08-12 07:02:32

使用正则表达式自行完成:

public class SpecialDateFormat
{
    private final static Pattern PATTERN = Pattern.compile("(\\d{2})[\\.\\/\\-](\\d{2})[\\.\\/\\-](\\d{4}) (\\d{2}):(\\d{2})");

    public static Date parse(String text) throws ParseException {
        Matcher m = PATTERN.matcher(text);
        if (m.matches()) {
            int dd = Integer.parseInt(m.group(1));
            int mm = Integer.parseInt(m.group(2));
            int yy = Integer.parseInt(m.group(3));
            int hh = Integer.parseInt(m.group(4));
            int mi = Integer.parseInt(m.group(5));

            // NOTE: Checking if values are in valid ranges omitted

            Calendar cal = Calendar.getInstance();
            cal.set(yy, mm - 1, dd, hh, mi, 0);

            return cal.getTime();
        }
        else {
            throw new ParseException("Unparseable date: " + text, 0);
        }
    }
}

但请注意,这确实允许混合不同的分隔符,例如“17-09/2009 12:00”将被允许。

Doing it yourself with a regular expression:

public class SpecialDateFormat
{
    private final static Pattern PATTERN = Pattern.compile("(\\d{2})[\\.\\/\\-](\\d{2})[\\.\\/\\-](\\d{4}) (\\d{2}):(\\d{2})");

    public static Date parse(String text) throws ParseException {
        Matcher m = PATTERN.matcher(text);
        if (m.matches()) {
            int dd = Integer.parseInt(m.group(1));
            int mm = Integer.parseInt(m.group(2));
            int yy = Integer.parseInt(m.group(3));
            int hh = Integer.parseInt(m.group(4));
            int mi = Integer.parseInt(m.group(5));

            // NOTE: Checking if values are in valid ranges omitted

            Calendar cal = Calendar.getInstance();
            cal.set(yy, mm - 1, dd, hh, mi, 0);

            return cal.getTime();
        }
        else {
            throw new ParseException("Unparseable date: " + text, 0);
        }
    }
}

Note however that this does allow mixing different separators, e.g. "17-09/2009 12:00" would be allowed.

七分※倦醒 2024-08-12 07:02:32

ParseExact 可以采用一系列格式。您仍然需要指定所有格式,但这是一个操作。

ParseExact can take an array of formats. You still have to specify all formats, but it's a single operation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文