1

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. I want to perform one functionality if I get format as date1.If I get date2 format then Another functionality. How to compare two date formats using strings.

Ex:

 if( date1.equals('dd/mm/yyyy')){

    //perform functionality

    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Sai Kishore Mani
  • 49
  • 1
  • 3
  • 11
  • 2
    Compare the date formats, or compare two dates in heterogeneous formats? – Andy Turner Jan 16 '17 at 14:30
  • But I need to compare String,How to compare date format using String – Sai Kishore Mani Jan 16 '17 at 14:36
  • What do you mean "compare `DateFormat`"? They're not inherently comparable, in the same way that one spoon is neither inherently greater nor less than another. – Andy Turner Jan 16 '17 at 14:39
  • Can you please give me a sample example. – Sai Kishore Mani Jan 16 '17 at 14:44
  • @SaiKishoreMani Could you please answer the question you are asked ? You are too broad, this is not clear – AxelH Jan 16 '17 at 15:09
  • @SaiKishoreMani What you want to do is `if(date is "dd/mm/yyyy") { get_Year_From_Last_4_Digits() } else if (date is "yyyy-mm-dd hh:mi:ss.S") { get_Year_From_First_4_Digits() }`... or something like that? Because **if** that is the case, maybe we can provide better solutions. Hence why Andy Turner and AxelH are asking you to be more specific. – walen Jan 16 '17 at 16:17

4 Answers4

2

Use RegEx:

    String date1 = "07/01/2017";
    if (date1.matches("^([0-9]{1,2}/){2}[0-9]{2,4}$")) {
        System.out.println("Date in MM/dd/yyyy format");
    } else if (date1.matches("^[0-9]{2,4}(-[0-9]{1,2}){2}\\s[0-9]{1,2}(:[0-9]{1,2}){2}\\.[0-9]{1,}$")) {
        System.out.println("Date in yyyy-MM-dd hh:mm:ss.t format");
    } else {
        System.err.println("Unsupported Date format.");
    }
Vadim
  • 4,027
  • 2
  • 10
  • 26
1

If you want to know if the date is in format mm/dd/yyyy or mm-dd-yyyy or something in the same idea, you probably need to use regex expressions.

You can check this for a way to implement it What is the regular expression for Date format dd\mm\yyyy?

Community
  • 1
  • 1
JFPicard
  • 5,029
  • 3
  • 19
  • 43
0

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<String> format = test("07-01-2017", "dd/mm/yyyy", "dd-mm-yyyy");
        if (format.isPresent())
            System.out.println(format.get());
    }

    public static Optional<String> 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<F, S> {
        public final F _1;
        public final S _2;

        public Pair(F _1, S _2) {
            this._1 = _1;
            this._2 = _2;
        }
    }
}
0

I guess, we can declare two date formats and parse the dates and compare the two Date instances. Here is sample code:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCompare {

    private static final String FORMAT1 = "MM/dd/yyyy";
    private static final String FORMAT2 = "yyyy-MM-dd hh:mm:ss";

    private Date parseDate(String format1, String format2, String dateStr) throws ParseException {
        boolean isException = false;
        Date date = null;
        try {
            date = parseDate(format1, dateStr);
        } catch (ParseException e) {
            isException = true;
        }
        if (isException) {
            date = parseDate(format2, dateStr);
        }
        return date;
    }

    private Date parseDate(String format1, String dateStr) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format1);
        return dateFormat.parse(dateStr);
    }

    public static void main(String[] args) throws ParseException {
        DateCompare compare = new DateCompare();
        Date date1 = compare.parseDate(FORMAT1, FORMAT2,"07/01/2017");
        Date date2 = compare.parseDate(FORMAT1, FORMAT2, "2017-07-01 00:00:00");

        if (date1.compareTo(date2) == 0) {
            System.out.println("Dates are equal.");
        } else {
            System.out.println("Dates are not equal.");
        }
    }
}
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
  • This answer misses the point: in the OP, we don't know whether the date string matches `FORMAT1` or `FORMAT2`. Your answer will result in uncaught `ParseExceptions`. – SME_Dev Jan 16 '17 at 15:48
  • @SME_Dev I have tried to address your point. Please check. Thanks for the feedback. – YoungHobbit Jan 16 '17 at 16:01
  • It is also workable solution, but it is up to taste. In general, I don't like to use exceptions in normal logic flow, just from performance and overload point of view. – Vadim Jan 16 '17 at 16:59