Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get present year value to string

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

like image 687
Frank Avatar asked Oct 05 '13 12:10

Frank


3 Answers

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);
like image 81
Rohit Jain Avatar answered Sep 23 '22 02:09

Rohit Jain


String thisYear = new SimpleDateFormat("yyyy").format(new Date());
like image 35
aianitro Avatar answered Sep 22 '22 02:09

aianitro


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();
like image 42
Gemtastic Avatar answered Sep 21 '22 02:09

Gemtastic