Ankit Dhingra
Ankit Dhingra

Reputation: 7004

Date in java with just year

My aim is to get a date in the format '{current year}-01-01 00:00:00' i.e. only the value for year changes with time. What is the best way to do that.

Using

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-01-01 00:00:00");
String format = simpleDateFormat.format(new Date());

doesnt seem clean enough.What other options do I have?

Upvotes: 2

Views: 8150

Answers (5)

Mr.Eddart
Mr.Eddart

Reputation: 10273

You can just do:

Calendar today = Calendar.getInstance()
String date = today.get(Calendar.YEAR) + "-01-01 00:00:00"

Upvotes: 0

Raku
Raku

Reputation: 591

Try using a Calendar like this:

new GregorianCalendar(Locale.CANADA).get(Calendar.YEAR);

Upvotes: 1

Aleks G
Aleks G

Reputation: 57346

You can do something like

Calendar cal = Calendar.getInstance();
cal.set(2011,1,1,0,0,0);

Then you can change the year of this object with

cal.set(Calendar.YEAR, [your-int-year]);

And print it in any way you want.

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

You can use a Calendar object with the following code:

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, year);

Upvotes: 4

RMT
RMT

Reputation: 7070

You should use a Calendar object. Much easier to manage, and if you need to get to a date there are methods for that.

  Calendar cal = Calendar.getInstance();
 //Set to whatever date you want as default
  cal.set(Calendar.YEAR, *year you want*);

Upvotes: 5

Related Questions