get present year value to string
58,149
Solution 1
You can simple get the year from Calendar
instance using Calendar#get(int field)
method:
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
String yearInString = String.valueOf(year);
Solution 2
String thisYear = new SimpleDateFormat("yyyy").format(new Date());
Solution 3
In Java 8 there's a collection called java.time
in which you easily can obtain the current year from your computer's clock.
To get the current year as an integer you can simply write:
int thisYear = Year.now().getValue();
To get it as a String:
String thisYear = Year.now().toString();
Solution 4
What about
Date currentDate = new Date();
String currentYear = String.valueOf(currentDate.getYear());
Solution 5
You can also do it like this:
String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
Author by
Frank
Updated on August 17, 2020Comments
-
Frank almost 4 years
I need to get the present year value in string so I did:
Calendar now = Calendar.getInstance(); DateFormat date = new SimpleDateFormat("yyyy"); String year = date.format(now);
It works on ubuntu but it's not working on windows 7.
Do you know why? Is there a safer way to do that?
Thanks
-
Rohit Jain over 10 years
Date#getYear()
is deprecated. -
Russia Must Remove Putin about 10 yearsYou should probably explain a bit.
-
lapo about 9 yearsAlso, that's
year-1900
. -
pczeus about 8 yearsThis is a low quality answer. You don't describe how this helps solve the issue, the answer is just code that is almost identical to what the original OP has and doesn't explain how this solves the issue.
-
user2100789 about 4 yearsI use this. SimpleDateFormat uses Calendar. Format examples: SimpleDateFormat