Frank
Frank

Reputation: 2173

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

Upvotes: 10

Views: 67304

Answers (10)

Rok T.
Rok T.

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

Nandkishor Gokhe
Nandkishor Gokhe

Reputation: 552

  //  enter code here
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy");
String year = format.format(date);

Upvotes: 0

jdev
jdev

Reputation: 5622

You can also do it like this:

String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));

Upvotes: 2

Gemtastic
Gemtastic

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

kizanlik
kizanlik

Reputation: 175

Java 8:

java.time.Year.now();

here is the link.

Upvotes: 3

aianitro
aianitro

Reputation: 886

String thisYear = new SimpleDateFormat("yyyy").format(new Date());

Upvotes: 14

Basil Bourque
Basil Bourque

Reputation: 339362

Time Zone

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.

Joda-Time

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

Rohit Jain
Rohit Jain

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

sunysen
sunysen

Reputation: 2351

try

Calendar now = Calendar.getInstance();
String year = String.valueOf(now.get(Calendar.YEAR));

Upvotes: 1

ssantos
ssantos

Reputation: 16536

What about

Date currentDate = new Date();
String currentYear = String.valueOf(currentDate.getYear());

Upvotes: 2

Related Questions