Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current year in android?

Tags:

java

android

I tried

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

but it is giving me compile time error that

Non-static method 'get(int)' cannot be referenced from a static context.

I am calling this method from call method of observable.

Observable.combineLatest(ob1 ob2,                 ob3, new Func3<String, String, String, Boolean>() {                     @Override                     public Boolean call(String a, String b, String c) {... 

I had also seen (new Date()).getYear(); but it is deprecated.

like image 367
Shunan Avatar asked Dec 28 '16 06:12

Shunan


People also ask

How can I get current date in Android?

getInstance(). getTime(); System. out. println("Current time => " + c); SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); String formattedDate = df.

Which code will return the current year in the phone?

get(Calendar. YEAR); and you are good to go.

How do I get the current date in Kotlin?

As Kotlin is interoperable with Java, we will be using the Java utility class and Simple Date Format class in order to get the current local date and time.


2 Answers

Because you need to create an instance first.

try this

Calendar.getInstance().get(Calendar.YEAR); 

and you are good to go.

like image 173
dsncode Avatar answered Sep 21 '22 14:09

dsncode


Yeah, you get an error because this is not a static method. First you need to create an instance of the Calendar class.
i.e.

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

If your min API version is <26, you can do a shorthand as well:

val yearInt = Year.now().value 
like image 31
Wajid Avatar answered Sep 20 '22 14:09

Wajid