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?
get(Calendar. MONTH) + 1; int year = calendar. get(Calendar. YEAR);
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).
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.
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.get(Calendar.YEAR)
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
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.
try this one..
Calendar instance = Calendar.getInstance();
currentMonth = instance.get(Calendar.MONTH);
currentYear = instance.get(Calendar.YEAR);
int month=currentMonth+1;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With