Take the 2-minute tour ×

I have two Strings

String withYear = "12/04/1988"

String withoutYear = "10/04"

The date format is MM/dd/yyyy

I am trying to determine whether a string contains a year or not.

Here is my code so far :

Calendar c= Calendar.getInstance();
c.setTime(dt.parse(withYear)); //dt is a SimpleDateFormat 'MM/dd/yyyy'
c.get(Calendar.YEAR) // = 1988

c.get(Calendar.YEAR);// = 1970
share|improve this question
Are they both are fixed in in format ? –  sᴜʀᴇsʜ ᴀᴛᴛᴀ Sep 30 '13 at 14:22
no exceptions the date format is right. –  user1940676 Sep 30 '13 at 14:22
if(myDateStr.split("/").length == 3), assuming this is a fixed format. –  Geobits Sep 30 '13 at 14:22
@Geobits could be a good workaround, is there any better way to check it with the Date object ? or the Calendar object? –  user1940676 Sep 30 '13 at 14:23
If you want to use the Date/Calendar objects, what's wrong with what you have? –  Geobits Sep 30 '13 at 14:26

4 Answers 4

up vote 4 down vote accepted

I think the easiest way to do this is to forget about making Date/Calendar objects altogether. You can simply check the String to see how many sections it has:

public static boolean containsYear(String dateStr){
    return dateStr.split("/").length == 3;
share|improve this answer

Your code is working perfectly, when you call dt.parse(withoutYear), the year is set automatically to the Epoch year (1970).


This parsing operation uses the calendar to produce a Date. All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information. For example, the year value of the parsed Date is 1970 with GregorianCalendar if no year value is given from the parsing operation. (emphasis mine)

If you don't expect any valid year values as 1970 then you can assume all dates with year==1970 were specified without a year.

A more complete solution would be to subclass GregorianCalendar and make the default value for field YEAR = -1;

share|improve this answer
        String data[] = withYear.split("/");
        String year =null ;
            year = data[2] ;
share|improve this answer

If you want, you can use YodaTime, its very easy to deal with time/dates, more about it here Yoda time getYear(). You can try to parse your String and then getYear().

Hope this helps.

share|improve this answer

Your Answer


