I am trying to get today\'s Year, Month and Date using following code;
Calendar calendar = Calendar.getInstance();
int thisYear = calendar.get(Calendar.YEAR);
L
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.
You can use SimpleDateFormat
Initialising as @SuppressLint("SimpleDateFormat") final SimpleDateFormat dateAndTime = new SimpleDateFormat("DD-MM-yy", Locale.getDefault());
and String timeStamp = dateAndTime.format(new Date());
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.
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
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.
try this one..
Calendar instance = Calendar.getInstance();
currentMonth = instance.get(Calendar.MONTH);
currentYear = instance.get(Calendar.YEAR);
int month=currentMonth+1;