How to get Current Year in YY Format in Java/Android

8k Views Asked by At

I am able to get Year in YYYY Format from my below Code. But I want in YY Format. Can anyone help?

Calendar c = Calendar.getInstance();

int seconds = c.get(Calendar.SECOND);
int hour = c.get(Calendar.HOUR_OF_DAY); // IF YOU USE HOUR IT WILL GIVE 12 HOUR USE HOUR_OF_DAY TO GET 24 HOUR FORMAT
int minutes = c.get(Calendar.MINUTE);
int date = c.get(Calendar.DATE);
int month = c.get(Calendar.MONTH) + 1; // in java month starts from 0 not from 1 so for december 11+1 = 12
int year = c.get(Calendar.YEAR);
2

There are 2 best solutions below

1
strash On

yep :)

int year = c.get(Calendar.YEAR) % 100;
1
its_meow On

You could do:

int fourDigYear = c.get(Calendar.YEAR)
String yrStr = Integer.toString(digyear).substring(2);
int year = Integer.parseInt(yrStr);

for example if the Calendar year was the int 2014, "year" would come out as the integer 14. This ensures that any year put in it will ALWAYS export the numbers past "yy". So I guarantee you will have no problems with it until the year 10000.

EDIT: To get this working for eternity, you can tweak it to this:

    int digyear = c.get(Calendar.YEAR);
    String yrStr = Integer.toString(digyear);
    String yrStrEnd = yrStr.substring(yrStr.length() - 2);
    int year = Integer.parseInt(yrStrEnd);