How to compare to String Date Formats in java?

前端 未结 4 856
被撕碎了的回忆
被撕碎了的回忆 2021-01-24 16:16

I am getting input as two types.

1.String date1 = \"07/01/2017\";
2.String date2 = \"\"2017-01-12 00:00:00.0\";

How to compare two date formats

4条回答
  •  -上瘾入骨i
    2021-01-24 17:16

    The solution with RegEx is good, but you can also do in this way:

    The first parameter is your string representation of the date. The next parameter is var arg. So you can pass as many date formats as you wish. It will try to parse and if success then returns proper format.

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Objects;
    import java.util.Optional;
    import java.util.stream.Stream;
    
    public class Test {
        public static void main(String[] args) {
            Optional format = test("07-01-2017", "dd/mm/yyyy", "dd-mm-yyyy");
            if (format.isPresent())
                System.out.println(format.get());
        }
    
        public static Optional test(String date, String... formats) {
            return Stream.of(formats)
                    .map(format -> new Pair<>(new SimpleDateFormat(format), format))
                    .map(p -> {
                        try {
                            p._1.parse(date);
                            return p._2;
                        } catch (ParseException e) {
                            return null;
                        }
                    })
                    .filter(Objects::nonNull)
                    .findFirst();
        }
    
        public static class Pair {
            public final F _1;
            public final S _2;
    
            public Pair(F _1, S _2) {
                this._1 = _1;
                this._2 = _2;
            }
        }
    }
    

提交回复
热议问题