Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get delimiter from a date string?

24.03.2018 02:34:22 how can I get the delimiter ('.') from a that kind of date string? Format can be different and delimiter can be these '.','-','/' also. Is there a way to do it with Java's date format classes?

like image 971
Joseph K. Avatar asked Feb 01 '26 23:02

Joseph K.


1 Answers

To answer this, we'll have to make a few assumptions:

  • As you've said, the delimiter can be -, /, or ., so I will be assuming no other delimiter is allowed.
  • From your only example in your question, we're looking for the delimiter of the date and not the time.
  • From your example, we'll assume that the date is always listed before the time.

Therefore, we should be able to solve this by looking for the first occurrence of any of those three characters:

public static Optional<Character> findDelimiter(String formattedDate) {
    for (char c : formattedDate.toCharArray()) {
        switch (c) {
            case '.':
            case '/':
            case '-':
                return Optional.of(c);
            case ' ':
            case '\t':
                return Optional.empty();
        }
    }

    return Optional.empty();
}

This will stop at the first instance of a space or a tab, assuming neither of those is the delimiter.

like image 197
Jacob G. Avatar answered Feb 03 '26 12:02

Jacob G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!