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
  • 386,424
  • 207
  • 554
  • 861
lokoko
  • 5,719
  • 5
  • 33
  • 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

4 Answers4

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
  • 10,983
  • 15
  • 91
  • 137
0

use DateFormat "yyyy", you will get year only

Kapil Vats
  • 5,415
  • 1
  • 25
  • 30
0
Calendar c = Calendar.getInstance(); 
c.setTime(sdf.parse(date));   // sdf is SimpleDateFormat
System.println(c.get(Calendar.YEAR)));
Paresh Mayani
  • 125,853
  • 70
  • 238
  • 294
  • 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,068
  • 3
  • 24
  • 38