3

How do i get only the year part of a date using DateUtils ? I tried using

DateUtils.FORMAT_SHOW_YEAR

but this seems to return even the month and date.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
lokoko
  • 5,785
  • 5
  • 35
  • 68
  • 1
    How did you use `DateUtils.FORMAT_SHOW_YEAR`? `DateUtils.FORMAT_SHOW_YEAR` is an `int` value used to specify the format when calling `DateUtils.formatDateTime()`. – Klas Lindbäck Feb 19 '13 at 09:14
  • DateUtils.formatDateRange(context, date.getTime(), date.getTime(), DateUtils.FORMAT_SHOW_YEAR); – lokoko Feb 19 '13 at 09:16
  • Try `DateUtils.formatDateTime(context, date.getTime(), DateUtils.FORMAT_SHOW_YEAR)`. – Klas Lindbäck Feb 19 '13 at 09:36

5 Answers5

3

No need to reinvent the wheel

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

To take the locale into account use the constructor SimpleDateFormat("template", Locale)

     SimpleDateFormat sdf = new SimpleDateFormat("yyyy", Locale.getDefault());
Droidman
  • 11,485
  • 17
  • 93
  • 141
0

use DateFormat "yyyy", you will get year only

Kapil Vats
  • 5,485
  • 1
  • 27
  • 30
0
Calendar c = Calendar.getInstance(); 
c.setTime(sdf.parse(date));   // sdf is SimpleDateFormat
System.println(c.get(Calendar.YEAR)));
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
  • Create a dateformat like this: SimpleDateFormat sdf = new SimpleDateFormat("your date format"); And in the line c.setTime(sdf.parse(date));, date is your input date in the format you provided when you create the SimpleDateFormat – harmjanr Feb 19 '13 at 09:15
  • 1
    @harmjanr he should do that job at least :) – Paresh Mayani Feb 19 '13 at 10:03
0

you can use

Calendar c = Calendar.getInstance(); 
int year = c.get(Calendar.YEAR);

you can check here

Community
  • 1
  • 1
Chirag Patel
  • 11,416
  • 3
  • 26
  • 38
0

I've used "YearOf". Seems a bit shorter. Hope it helps:

int currentyear = Dateutils::YearOf(Now());