In this article we will show you the solution of java get year from date, obtaining the year value from a Date object is known as "getting the year from date" in Java. The entire year, the month, day, hour, minute, second, & millisecond are all represented by the Date class.
It's important to keep in mind that the getYear() method of the Date class returns the number of years since 1900 rather than the year value in which the date falls.
Therefore, we must multiply the returned value by 1900 in order to obtain the actual year.
Using this method, we can extract the year value from a Date object, which is important for a variety of applications that deal with dates and timings.
Now move to the concept of Java get year from date.
Step By Step Guide On Java Get Year From Date :-
import java.util.Date; public class JavaDateGetYearExample1 { public static void main(String[] args) { Date d=new Date(); int year=d.getYear(); System.out.println("Date object's year is: "+year); System.out.println("To determine the current year, multiply the value of the year acquired from this date object by 1900."); int currentYear=year+1900; System.out.println("The present year is: "+currentYear); } }
- Here, you can see how we created a straightforward Java programme to show how to use Java's Date class to determine the current year.
- In the first line of code, we import a date class within the java.util package.
- Classes for representing the time and date in Java are available in this package.
- A new Date object is then generated using its default constructor in the main() method.
- The current time and the date are used to initialise the Date object.
- The Year property of the Date object is then retrieved by using the getYear() function on the Date object.
- It's crucial to keep in mind that this method delivers the duration since 1900.
- To retrieve the real year, 1900 must be multiplied by the year value acquired from the getYear() method.
- The year received from the Date object is then printed, followed by a message describing how to find the present year using the getYear() method.
- The result is saved in the currentYear variable. Next, the current year is calculated through Adding 1900 to the year acquired from the Date object.
- The current year is then written along with a message following the printing of this variable.
- A java.time package, which launched in Java 8, makes working with dates and times more modern and efficient.
Conclusion :-
Therefore, we learned the use of Java's get year from date concept.
We also discovered that the provided code serves as a straightforward illustration of how to acquire the current year in Java by using the Date class.
To work with dates and times in contemporary Java programmes, it is advised to use the java.time package.
I hope this article on java get year from date helps you and the steps and method mentioned above are easy to follow and implement.