user1940676
user1940676

Reputation: 4448

Check if date String contains a year

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.setTime(dt.parse(withoutYear));
c.get(Calendar.YEAR);// = 1970

Upvotes: 0

Views: 2132

Answers (4)

Ron
Ron

Reputation: 1508

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

From SimpleDateFormat: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

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;

Upvotes: 3

anotherUser
anotherUser

Reputation: 561

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.

Upvotes: 0

Geobits
Geobits

Reputation: 22342

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;
}

Upvotes: 4

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26104

        String data[] = withYear.split("/");
        String year =null ;
        if(data.length==3){
            year = data[2] ;
            System.out.println(year);
        }

Upvotes: 2

Related Questions