0

I would like to create a method which takes input as Date and check what is the format of it or whether it is matching with particular format.

myMethod(Date date){
    String format = "yyyy-MM-dd";
    //Here I would like to compare that 'date' is in the required format
}

Here, I should accept Date type only not String type.

Jyo
  • 203
  • 4
  • 18
  • 1
    `Date` doesn't have a format. Moreover, a `Date` isn't even a *date*; for what you appear to want here, use `LocalDate`. – Andy Turner Feb 24 '20 at 07:03
  • A `Date` hasn’t got a format. So it isn’t. – Ole V.V. Feb 24 '20 at 07:03
  • I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Feb 24 '20 at 07:04
  • 1
    @OleV.V. how are your toes? I mean, we are treading on each others' feet here ;) – Andy Turner Feb 24 '20 at 07:06
  • 1
    You can try using a fixed number of predefined date formats and then use SimpleDateFormat to parse the date to test against. Use the first one that doesn't throw an exception. Note however that there's no way to do this with complete certainty. There are simply too many alternatives, and they are often ambiguous (consider e.g. MM/dd/yyyy versus dd/MM/yyyy). – Aman Kumar Soni Feb 24 '20 at 07:18
  • @AmanKumarSoni No, you’re on the wrong track. (1) `SimpleDateFormat` is notoriously troublesome and long outdated, don’t suggest it. (2) Parsing is what we can do with a string, but the questioner has got a `Date`, not a `String`. – Ole V.V. Feb 24 '20 at 07:31
  • @Andy Turner @OleV.V. Thank you for your reply. I could not catch your point. I am getting Date from UI and I have to check whether it is `yyyy-MM-dd` or not. Can I have sample code snippet? – Jyo Feb 24 '20 at 09:54
  • Sure. I have added a 4th link to an original question giving lots of code snippets for exactly that. For your purpose I recommend [the answer by Basil Bourque](https://stackoverflow.com/a/39649815/5772882) and [the one by vijay](https://stackoverflow.com/a/57268013/5772882). If you tell us how the characters that the user types get transmitted from the keyboard to your method, we can probably guide you still more precisely. – Ole V.V. Feb 24 '20 at 13:18

0 Answers0