-1

I have a project requirement. There are values in a .txt as -

 02/01/2017 00:00:00

Now I need to have some rules to check if this value in the data file is of type Date. How can I do that? Thanks. I am new to Java so any help much appreciated. Thanks

bably
  • 1,065
  • 5
  • 17
  • 27
  • 3
    Try to parse the String to a date. If it works your string is a date. – OH GOD SPIDERS Apr 26 '17 at 10:36
  • What does the surrounding text look like? How do you store the file contents after reading it? Date or LocalDate? – Robin Topper Apr 26 '17 at 10:36
  • Convert that string into date format object if it gets convert its date if it gives any exception its not a date – Amit Gujarathi Apr 26 '17 at 10:38
  • 1
    Possible duplicate of [how to convert String into Date time format in JAVA?](http://stackoverflow.com/questions/16910344/how-to-convert-string-into-date-time-format-in-java) – px06 Apr 26 '17 at 10:45
  • 1
    @OHGODSPIDERS, it’s not really that simple. With lenient parsing, invalid days will be accepted. Lenient is the default for the old `SimpleDateFormat`, fortunately not for the new `java.time` classes like `LocalDateTime`. – Ole V.V. Apr 26 '17 at 11:02
  • Even though you say `Date` (possibly referring to `java.util.Date`), I would still recommend using the `java.time` classes if you can. Look into `LocalDateTime` and `DateTimeFormatter`. – Ole V.V. Apr 26 '17 at 11:04
  • I answered [a very similar question](http://stackoverflow.com/questions/43614449/i-want-to-write-a-generic-function-where-for-these-valid-date-format-mm-dd-yyyy/43615206?noredirect=1#comment74297287_43615206) with a `java.time` api solution yesterday. The pre-Java8 version is now between the answers here – Robin Topper Apr 26 '17 at 11:05
  • With a little search effort you should have been able to find enough similar questions to put a solution together yourself. If in that proces you get stuck, please ask a more specific question, demonstrating what you have tried and in what way it failed or was insufficient. – Ole V.V. Apr 26 '17 at 11:07
  • Example of a similar question: [How to check validity of Date String?](http://stackoverflow.com/questions/4010258/how-to-check-validity-of-date-string). See if you cannot use that and adopt to your needs. – Ole V.V. Apr 29 '17 at 05:02

7 Answers7

1

Try to parse it to date. If it throws ParseException then it is not a date.

String dateString = "02/01/2017 00:00:00";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss"); 
Date date;
try {
    date = df.parse(dateString);
} catch (ParseException e) {
    e.printStackTrace();
}
Pooja Arora
  • 574
  • 7
  • 19
1

If you just want valid days, use non-lenient parsing:

String dateString = "02/28/2017 00:00:00";

DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
df.setLenient(false);
Date date;
try {
    date = df.parse(dateString);
    System.out.println(date);
} catch (ParseException e) {
    e.printStackTrace();
}

This will throw an exception for non-existing days like the 31st of February

Robin Topper
  • 2,295
  • 1
  • 17
  • 25
1
  1. Methord 1

    Date dt = new Date(); //this should your Dynamic object
    
    if (dt.getClass().equals(new Date().getClass())) 
    {
      //if its date object
    }
    
  2. Methord 2

     if(dt instanceof  Date){
       //if its date object
     }
    
  • I know the question isn’t clear, but I think it’s clear enough that the data asked about comes from a text file ( extension `.txt`). So I can’t see how your answer is relevant? Also I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead depending on requirements use `LocalDateTime` or `Instant`; both are from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 19 '21 at 16:02
  • 1
    I understood just now .... sorry ....you have to use only try catch method.... maybe you can create a different function and write all types of date and all formates in it ...call that function and get a boolean value return... I dont think some other option will be there – Guru Nitin Mar 21 '21 at 02:37
0

Use this to check date

String sDate1="31/12/1998 00:00:00";  
try{
  Date date1=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse(sDate1);  `
} 
catch(Exception e)
{
  //Not a date..
} 
Dishonered
  • 8,449
  • 9
  • 37
  • 50
0

You can use regular expressions to check the format

public boolean isDate(String s){
String pattern= "([0-9]{2})/([0-9]{2})/([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})";
return s.matches(pattern);}
  • 1
    So ... `"99/99/9999 00:00:00"` would be a date? – Robin Topper Apr 26 '17 at 10:50
  • No. This is the direction to thinking. For example, here is http://stackoverflow.com/questions/15491894/regex-to-validate-date-format-dd-mm-yyyy correct date recognition. – Алексей Мокрев Apr 26 '17 at 10:55
  • 2
    @АлексейМокрев I very much doubt that you can properly check dates with a regex, especially 29th of Feb on leap years, unless it becomes an undecipherable mess. Trying to parse the date is much cleaner in my opinion (and less error prone). – assylias Apr 26 '17 at 11:12
0

Here’s the Java 8 solution (it can be made to work in Java 6 and 7 too when you use the ThreeTen Backport).

private static final DateTimeFormatter DATE_TIME_FORMAT 
        = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss")
                .withResolverStyle(ResolverStyle.STRICT);

public static boolean hasTypeDate(String stringFromTxt) {
    try {
        DATE_TIME_FORMAT.parse(stringFromTxt);
        return true;
    } catch (DateTimeParseException dtpe) {
        return false;
    }
}

Stay away from SimpleDateFormat for new code. It has had its time, it’s been outdated for a while now.

If you intended the day of month first (if 02/01/2017 means January 2nd), you need the format pattern dd/MM/uuuu HH:mm:ss instead.

If you need to know which date and time was in the .txt, use:

        LocalDateTime dateTime = LocalDateTime.parse(stringFromTxt, DATE_TIME_FORMAT);

Link: ThreeTen Backport: java.time classes for Java 6 and 7.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
-1
public static boolean isValidDate(String inDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    try {
      dateFormat.parse(inDate.trim());
    } catch (ParseException pe) {
      return false;
    }
    return true;
  }

public static void main(String[] args) {
 String file = "/path/to/your/file.txt";

try {

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    String line;
    while ((line = br.readLine()) != null) {
        // do something with line
    }
    br.close();
   isValidDate(line));
   //do what you want :)
  }
Yahya Hussaini
  • 88
  • 1
  • 1
  • 13