Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Year, Month and Date in Android

I am trying to get today's Year, Month and Date using following code;

Calendar calendar = Calendar.getInstance();

int thisYear = calendar.get(Calendar.YEAR);
Log.d(TAG, "# thisYear : " + thisYear);

int thisMonth = calendar.get(Calendar.MONTH);
Log.d(TAG, "@ thisMonth : " + thisMonth);

int thisDay = calendar.get(Calendar.DAY_OF_MONTH);
Log.d(TAG, "$ thisDay : " + thisDay);

But it gives "2012 for year 1 for month and 28 for date" which is not today's date. What I have done wrong?

like image 529
Eranga Peris Avatar asked Sep 02 '12 06:09

Eranga Peris


People also ask

How to get current year month and day in android?

get(Calendar. MONTH) + 1; int year = calendar. get(Calendar. YEAR);

How to get day month from date in android?

If you know for certain that date and time-of-day in the LocalDateTime was meant to represent a moment in UTC, use OffsetDateTime class. OffsetDateTime odt = ldt. atOffset( ZoneOffset. UTC ) ; // Assign UTC (an offset of zero hours-minutes-seconds).


6 Answers

Would I be correct in assuming this is running on a Emulator? If so, Set the emulator date correctly, and it should be correct.

From memory, that code should do what you expect.

like image 59
James Avatar answered Oct 14 '22 04:10

James


Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.get(Calendar.YEAR)
like image 26
Sujewan Avatar answered Oct 14 '22 05:10

Sujewan


import java.util.Calendar;
import java.util.TimeZone;
import android.widget.Toast;

Calendar calendar = Calendar.getInstance(TimeZone.getDefault());

int currentYear = calendar.get(Calendar.YEAR);
int currentMonth = calendar.get(Calendar.MONTH) + 1;
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);

Toast.makeText(this,"Today's Date: " + currentYear + currentMonth + currentDay, Toast.LENGTH_SHORT).show();

"TimeZone" will work great if your application targets for Android API 27 platform or above

like image 27
Moeed Ahmed Avatar answered Oct 14 '22 05:10

Moeed Ahmed


The month starts from zero so you have to add 1 with the given month to show the month number we are familiar with.

int thisMonth = calendar.get(Calendar.MONTH);
Log.d(TAG, "@ thisMonth : " + (thisMonth+1));

This will show you the current month starting with 1.

like image 44
Shalauddin Ahamad Shuza Avatar answered Oct 14 '22 05:10

Shalauddin Ahamad Shuza


try this one..

 Calendar instance = Calendar.getInstance();
 currentMonth = instance.get(Calendar.MONTH);
 currentYear = instance.get(Calendar.YEAR);

 int month=currentMonth+1;
like image 43
Ganesh Giri Avatar answered Oct 14 '22 03:10

Ganesh Giri


I tried your code and it is giving correct output. You should try checking time in your emulator/phone on which you are trying this code.

According to getInstance docs, it sets to current date and time by Default.

like image 20
AAnkit Avatar answered Oct 14 '22 04:10

AAnkit