Reputation: 2173
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
Upvotes: 10
Views: 67304
Reputation: 409
In Java versions prior Java 8 you could also use java.sql.Date class. Convert to String and substring the year:
String currentYear = new java.sql.Date(System.currentTimeMillis()).toString().substring(0, 4);
Upvotes: 0
Reputation: 552
// enter code here
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy");
String year = format.format(date);
Upvotes: 0
Reputation: 5622
You can also do it like this:
String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
Upvotes: 2
Reputation: 6433
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();
Upvotes: 5
Reputation: 886
String thisYear = new SimpleDateFormat("yyyy").format(new Date());
Upvotes: 14
Reputation: 339362
Both the question and accepted answer ignore the question of time zone. At the time of a new year, the year number varies depending on your time zone.
The bundled java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.
Example in Joda-Time.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = DateTime.now( timeZone );
int year = dateTime.year().get();
Upvotes: 1
Reputation: 213311
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);
Upvotes: 27
Reputation: 2351
try
Calendar now = Calendar.getInstance();
String year = String.valueOf(now.get(Calendar.YEAR));
Upvotes: 1
Reputation: 16536
What about
Date currentDate = new Date();
String currentYear = String.valueOf(currentDate.getYear());
Upvotes: 2