2

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?

Ankit Dhingra
  • 6,534
  • 6
  • 31
  • 34
  • 3
    Why use a Date at all? Just curious. – Rob Hruska Jul 13 '11 at 12:24
  • I need the current year..I thought date was the way to do that.. – Ankit Dhingra Jul 13 '11 at 12:30
  • 1
    Ok. The answers using Calendar are probably the better way. You might also be interested in the answers to [this question](http://stackoverflow.com/questions/136419/get-integer-value-of-the-current-year-in-java). – Rob Hruska Jul 13 '11 at 12:47
  • 1
    If you have found your answer accept the one that has helped you the most so others can learn from it. – RMT Jul 13 '11 at 12:56

5 Answers5

5

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*);
RMT
  • 7,040
  • 4
  • 25
  • 37
4

You can use a Calendar object with the following code:

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, year);
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • 1
    `getInstance()` will give you the current time, including the month, day, hour, minute, etc. `clear()` resets all of those fields, so you get the 1st day of January at midnight for whichever year you're interested in. – Anthony Grist Jul 13 '11 at 15:53
1

Try using a Calendar like this:

new GregorianCalendar(Locale.CANADA).get(Calendar.YEAR);
Raku
  • 591
  • 2
  • 13
0

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.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
0

You can just do:

Calendar today = Calendar.getInstance()
String date = today.get(Calendar.YEAR) + "-01-01 00:00:00"
Mr.Eddart
  • 10,050
  • 13
  • 49
  • 77