6

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

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
Tarski
  • 5,132
  • 4
  • 35
  • 46

7 Answers7

5

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

kgiannakakis
  • 96,871
  • 26
  • 155
  • 191
5

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.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • Thanks, I'm gonna start working on a generic date parser for our code base and this will be a good start – Tarski Sep 18 '09 at 09:51
4

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?

Tim Büthe
  • 58,799
  • 16
  • 82
  • 126
2

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.

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
1

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));
} 
NomeN
  • 15,253
  • 6
  • 29
  • 33
  • Because \ is an escape character in Java string literals, you'd have to double each \: "\\d\\d[\\.\\/\\-]\\d\\d[\\.\\/\\-]\\d\\d\\d\\d \\d\\d:\\d\\d" – Jesper Sep 18 '09 at 09:49
  • You are mistaken - you would still need to write "\\d" in your Java source code, regardless if this is a regular expression or not. – Jesper Sep 18 '09 at 10:06
  • Now I had to go and check, you are absolutely right sir. That is ugly as hell, they could so easily just have used another escape character. – NomeN Sep 18 '09 at 10:23
0

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.

Jesper
  • 186,095
  • 42
  • 296
  • 332
  • I call blatant stealing of concept ;-), you'll see that I've worked in the different separator checking with not much effort. – NomeN Sep 18 '09 at 10:29
  • And apparently you do not need to escape any of the characters in between the [], not even the period. – NomeN Sep 18 '09 at 10:32
-3

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

Tor Haugen
  • 18,547
  • 8
  • 40
  • 59