Java Program to Get Year From Date
Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, which is how to get a year from date using Java.
There are many ways to get a year from date of which frequently used two methods are listed below.
- Using get() method LocalDate class
- Using get() method of Calendar class
- Using split() method of String class
Let us discuss each of them in detail alongside implementing the methods
Method 1: Using get() method of LocalDate class
The get() method of LocalDate class in Java method gets the value of the specified field from this Date as an int.
public int get(TemporalField field)
Parameter: This method accepts a parameter field which is the field to get and not necessarily null.
Return Value: It returns the value for the field.
Exceptions: It throws three exceptions namely as follows:
- DateTimeException: This exception is thrown if a value for the field cannot be obtained or the value is outside the range of valid values for the field.
- UnsupportedTemporalTypeException: This exception is thrown if the field is not supported or the range of values exceeds an int
- ArithmeticException: This exception is thrown if numeric overflow occurs
Method 2: Using get() method of Calendar class
The get(int field_value) method of Calendar class is used to return the value of the given calendar field in the parameter.
public int get(int field)
Parameters: The method takes one parameter field_value of integer type and refers to the calendar whose value is needed to be returned.
Return Value: The method returns the value of the passed field.
Note: In above program, get() method is used to get the year from the specified date.
Method 3: Using split() method of String class
This method does break a given string around matches of the given regular expression.
Parameters: It takes two parameters namely:
- Regex: A delimiting regular expression
- Limit: The resulting threshold
Return type: An array of strings computed by splitting the given string.
Exceptions: PatternSyntaxException – if the provided regular expression’s syntax is invalid.
Here split() function of String class is used to split a specified date string according to the given pattern, and it returns an array of string.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.