简体   繁体   中英

Parse any string to Sql date

I wonder if it's possible to parse any string (at least to try) to sql Date without specifing the string format? In other words I want to make a generic method who take as input a string and return an sql Date.

For instance I have:

String date1="31/12/2099";
String date2="31-12-2099";

and call parseToSqlDate(date1) and parseToSqlDate(date2) which will returns sql dates.

Short answer: No

Why: Parsing any string to a valid date is a task you as an intelligent being could not do (there is no "logical" way to determine the correct date), so you cannot "tell" a computer(program) to do that for you (see JGrice's comment, and there we still have 4-digit years).

Long answer: Maybe, if you are willed to either take risks or do not need a high rate of success.

How:

  1. Define your minimal (format) requirements of a date. Eg "a minimal date contains 1-8 numbers; 01/01/2001 , 01-01-01 , 01.01 (+current year) , 1.1 (+current year), 1 (+current month + current year) and/or "..contains 1-6 numbers and the letters for months"; 01-Jan-2001 and so on.

  2. Split the input along any non-number/non-month-name characters, with a regex like [^0-9a-zA-Z] (quick thought, may hold some pitfalls)

  3. You now have 1 to 3 (actually more if eg the time is included) separate numbers + 1 month name which can be aligned for year/month/day any way you like

For this "alignment", there are several possibilities:

  • Try a fixed format at first, if it "fits", take it, else try another (or fail)
  • (only of you get more than one entry at a time) guess the format by assuming all entries have the same (eg any number block containing values > 12 is not a month and > 31 is not a day)

BUT , and this is a big one, you can expect any such method to become a major PITA at some point, because you can never fully "trust" it to guess correctly (you can never be sure to have missed some special format or introduced some ambiguous interpretation). I outlined some cases/format, but definitely not all of them, so you will refine that method very often if you actually use it.

Appendix to your comment: "May be to add another parameter and in this way to know where goes day , month and so on?" So you are willed to add "pseudo-format-string" parameter specifying the order of day, month and year; that would make it a lot easier (as "simply" filtering out the delimiters can be achieved).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM