-1

how to validate date format MM/YYYY as String example-

09/20 false

13/5651 false

3/2104 true

03/2010 true

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Sumit Sharma
  • 23
  • 2
  • 5
  • 1
    i tried with sampleDateFormat but it gives 09/20 as true but i need date as full part in 4 numbers – Sumit Sharma Oct 14 '18 at 18:45
  • 1
    Right, don’t use `SimpleDateFormat`, it’s hard to get right, and the class is long outdated. Use `YearMonth` and `DateTimeFormatter` from java,time, the modern Java date and time API. Also I don’t think you can force `SimpleDateFormat` to reject a 2 or 3 digit year. – Ole V.V. Oct 14 '18 at 18:56
  • Related: [How to sanity check a date in Java](https://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java). Your search engine will be happy to show you more related and inspirational questions and answers. – Ole V.V. Oct 14 '18 at 19:00
  • You can use a **Regular Expression** (RegEx) along with the **String#matches()** method to validate your **specific** date format, for example: `boolean dateIsValid = dateString.matches("^(0?[1-9]|1[012])\\/[0-9]{4}$");`. I'm not placing this as an answer since you have so many great ones already but if you want an explanation of this RegEx then copy/paste the expression **^(0?[1-9]|1[012])\/[0-9]{4}$** into [RegEx101.com](https://regex101.com/) and read the explanation there. – DevilsHnd - 退職した Oct 14 '18 at 20:00

3 Answers3

2

Use YearMonth class.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/uuuu" ) ;
YearMonth ym = YearMonth.parse( "3/2018" , f ) ;

Trap for DateTimeParseException to detect invalid input.


Tip: Use standard ISO 8601 formats for exchanging date-time values as text. For year-month: YYYY-MM

The java.time classes use these standard formats by default.

YearMonth.parse( "2018-03" ) 

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

What you want is a customized method because you place special constraints to the validity of the date.
The following passed all your 4 examples:

public static boolean validDate(String date) {
    date = date.trim();
    if (date.length() < 6)
        return false;

    String[] parts = date.split("/");
    if (parts.length != 2)
        return false;

    int month = 0;
    try {
        month = Integer.parseInt(parts[0]);
    } catch (NumberFormatException e) {
        e.printStackTrace();
        return false;
    }
    if (month < 1 || month > 12)
        return false;

    int year = 0;
    try {
        year = Integer.parseInt(parts[1]);
    } catch (NumberFormatException e) {
        e.printStackTrace();
        return false;
    }
    if (year < 1000)
        return false;

    return true;
}

public static void main(String[] args) {
    String s1 = "09/20";
    String s2 = "13/5651";
    String s3 = "3/2104";
    String s4 = "03/2010";

    System.out.println(s1 + " " + validDate(s1));
    System.out.println(s2 + " " + validDate(s2));
    System.out.println(s3 + " " + validDate(s3));
    System.out.println(s4 + " " + validDate(s4));
}

will print:

09/20 false
13/5651 false
3/2104 true
03/2010 true

I'm not sure about this part:

if (year < 1000)
    return false;

you can change it if you like.

forpas
  • 160,666
  • 10
  • 38
  • 76
  • Thanks for the suggestion. I disagree, though. There’s nothing special about the asker’s constraints and therefore no need for a custom solution.The standard library methods used in [Basil Bourque’s answer](https://stackoverflow.com/a/52806050/5772882) handle the validation just fine. If needed you may combine with a range check using `ym.isBefore(YM_MIN)` and similar for a maximum `YearMonth`. – Ole V.V. Oct 15 '18 at 00:36
0
public boolean isThisDateValid(String dateToValidate, String dateFromat){

    if(dateToValidate == null){
        return false;
    }

    SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
    sdf.setLenient(false);

    try {

        //if not valid, it will throw ParseException
        Date date = sdf.parse(dateToValidate);
        System.out.println(date);

    } catch (ParseException e) {

        e.printStackTrace();
        return false;
    }

    return true;
}

Referensi https://www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/

  • Thanks for wanting to contribute. Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Dec 05 '18 at 11:24