6

If input is 01-01-2015 it should change to 2015-01-01.
If input is 2015-01-01 it should change to 01-01-2015.
I used SimpleDateFormat but didn't get the correct output:

//Class to change date dd-MM-yyyy to yyyy-MM-dd and vice versa
public class ChangeDate {
  static SimpleDateFormat formatY = new SimpleDateFormat("yyyy-MM-dd");
  static SimpleDateFormat formatD = new SimpleDateFormat("dd-MM-yyyy");

  //This function change dd-MM-yyyy to yyyy-MM-dd
  public static String changeDtoY(String date) {
    try {
      return formatY.format(formatD.parse(date));
    }
    catch(Exception e) {
      return null;
    }
  }

  //This function change yyyy-MM-dd to dd-MM-yyyy
  public static String changeYtoD(String date) {
    try {
      return formatD.format(formatY.parse(date));
    }
    catch(Exception e) {
      return null;
    }
  }
}

I want some condition that automatically detects the date's pattern and change to the other format.

honk
  • 9,137
  • 11
  • 75
  • 83
Sreemat
  • 616
  • 10
  • 28

5 Answers5

7

There are 2 options:

  1. Try to check with regular expression sth. like:

    if (dateString.matches("\\d{4}-\\d{2}-\\d{2}")) {
        ...
    }
    
  2. Try to convert to first pattern, if it throws exception, try to convert to another pattern (but it is bad practice to do so)

Tom
  • 16,842
  • 17
  • 45
  • 54
Azat Nugusbayev
  • 1,391
  • 11
  • 19
  • i will try the first option i have tried the second option but it convert and gave inappropriate date.Thank you – Sreemat Dec 25 '15 at 19:22
  • Using exceptions should be restricted to actual exceptions, not as handling for intended behavior. -1. – CosmicGiant Dec 25 '15 at 19:31
  • It doesn't throw exception @AlmightyR – Sreemat Dec 25 '15 at 19:43
  • @Sreemat I didn't say it does. The second method uses exceptions to implement normal, expected behavior. This is bad practice. And that's what makes (half) the answer bad. -1 will be lifted once bad method is removed. – CosmicGiant Dec 25 '15 at 19:47
2

Regex Is Overkill

For date-time work, no need to bother with regex.

Simply attempt a parse with one format, trapping for the expected exception. If the exception is indeed thrown, attempt a parse with the other format. If an exception is thrown, then you know the input is unexpectedly in neither format.

java.time

You are using old troublesome date-time classes now supplanted by the java.time framework built into Java 8 and later. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Oracle Tutorial.

LocalDate

The new classes include one, LocalDate, for date-only values without time-of-day. Just what you need.

Formatters

Your first format may be the standard ISO 8601 format, YYYY-MM-DD. This format is used by default in java.time.

If this first parse attempt fails because the input does not match ISO 8601 format, a DateTimeParseException is thrown.

LocalDate localDate = null;  
try {
    localDate = LocalDate.parse( input );  // ISO 8601 formatter used implicitly.
} catch ( DateTimeParseException e ) {
    // Exception means the input is not in ISO 8601 format.
}

The other format must be specified by a coded pattern similar to what you are doing with SimpleDateFormat. So if we catch the exception from the first attempt, make a second parse attempt.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM-dd-yyyy" );
LocalDate localDate = null;  
try {
    localDate = LocalDate.parse( input );
} catch ( DateTimeParseException e ) {
    // Exception means the input is not in ISO 8601 format.
    // Try the other expected format.
    try {
        localDate = LocalDate.parse( input , formatter );
    } catch ( DateTimeParseException e ) {
        // FIXME: Unexpected input fit neither of our expected patterns.
    }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    Using exceptions to handle non-exceptional behavior (/for flow-control) is very bad practice. -1. – CosmicGiant Dec 26 '15 at 12:45
  • 1
    Exception handling here is required as the core Java method called declares the exception. If the try/catch is omitted, the code will not compile successfully. This example is catching the specific DateTimeParseException thrown by the parse method instead of plain Exception or Throwable, so this example shows concise and correct code. – Jason Plurad Dec 26 '15 at 14:11
  • @JasonPlurad Hm, `DateTimeParseException` is a `RuntimeException` so the compiler does not require explicit exception handling (throws or catch). Or do you speak about something else? Anyway, `LocalDate.parse(...)` will compile without try/catch - code. If this solution is elegant is another question however. – Meno Hochschild Dec 26 '15 at 21:12
  • Ah yes, you are correct. It is a RuntumeException. If a method explicitly declares a throw for a RuntimeException, I would still surround it with try/catch block even if it compiled without it. Thanks. – Jason Plurad Dec 26 '15 at 22:41
  • @JasonPlurad My comment on bad practice was referring to *" If the exception is indeed thrown, attempt a parse with the other format."* – CosmicGiant Dec 27 '15 at 16:23
  • @JasonPlurad *"This example is catching the specific DateTimeParseException thrown by the parse method instead of plain Exception or Throwable (...)"* - This has nothing to do with my critique. ••• *"(...) so this example shows concise and correct code."* - Concise? Yes. Correct? ***No***. – CosmicGiant Dec 30 '15 at 21:30
0

Read up about Pattern, Matcher, and Regular Expressions.

Java code (based on OP):

if (date.matches("\\d{2}-\\d{2}-\\d{4}")){
  //convert D format to Y format...
} else if(date.matches("\\d{4}-\\d{2}-\\d{2}")){
  //convert Y to D...
} else {
  throw new IllegalArgumentException("Received date format is not recognized.");
}

Note: This Match-Pattern can be improved with capture groups.
Ex: "\\d{4}(-\\d{2}){2}" or "(-?\\d{2}){2}\\d{4}"

CosmicGiant
  • 6,275
  • 5
  • 43
  • 58
0

See: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/datetime/iso/examples/StringConverter.java

Non-ISO Date Conversion https://docs.oracle.com/javase/tutorial/datetime/iso/nonIso.html

Adding a new Chronology that identifies the ISO Date either way is another compatible (breakproof) means to input the Date Data and store it in correct Structures (where other Functions can easily operate upon the Data). See: https://docs.oracle.com/javase/8/docs/api/java/time/chrono/Chronology.html

The 'regex method' can be broken by erroneous input and leaves no means to return a standard error in response to whatever was input (to get a standard identical result everywhere).

See the answer provided by User "Tardate" in this Thread: How to sanity check a date in java .

You want bulletproof input and to store it in correctly identified Structures in order to easily manipulate it with other Functions.

Community
  • 1
  • 1
Rob
  • 1,487
  • 2
  • 25
  • 29
-2

Just compare the position of first '-' character in date string.

  • 1
    Assumes the reader knows or understands "how", at which point they would probably not be asking/reading for this answer. -1. – CosmicGiant Dec 25 '15 at 20:01
  • @SantoshVishwakarma As it is now, this Answer should have been posted as a Comment. Please add some more explanation and example code to become a full-fledged Answer. – Basil Bourque Dec 26 '15 at 17:50