Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing String to Date when sometimes year is missing and sometimes not

Tags:

java

string

date

I am parsing multiple String objects containing date in format of mm/dd/yyyy into Date objects using SimpleDateFormatter

Problem I am facing is that, some String contain complete date means it is mm/dd/yyyy while some Strings do not contain year and comes in this format mm/dd

I am using this format to parse dates MM/dd/yyyy but everytime I get a String with only month and day, I get parsing exception.

I want to know, is there any way by which if a year field is missing then I can use something like 0000 or I need to tackle it into exception body only?

like image 496
Abhi Avatar asked Jan 29 '26 15:01

Abhi


2 Answers

Just create 2 separate SimpleDateFormat instances, one that you have and a second one with day and month only. You analyze the string first and pass it to the correct formatter.

Or pass it to the first one and if an exception is thrown, pass it to the second one.

like image 177
Dan D. Avatar answered Feb 01 '26 05:02

Dan D.


as far as i know you can create an instance of SimpleDateFormat that does not "need" an year. So just use an try-catch-Block

 try{
    //try formatting with simpledate instance with year
 }catch (Exception thrown when no year){
    try{
       //try formatting with simple date instace without year
    } catch (Exception e)
       //something went wrong both did not accept it
    }
}
like image 45
nurgan Avatar answered Feb 01 '26 03:02

nurgan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!