Getting Year, Month and Date in Android

前端 未结 9 1921
走了就别回头了
走了就别回头了 2021-02-06 21:04

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         


        
相关标签:
9条回答
  • 2021-02-06 21:40

    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.

    0 讨论(0)
  • 2021-02-06 21:42

    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());

    0 讨论(0)
  • 2021-02-06 21:46

    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.

    0 讨论(0)
  • 2021-02-06 21:50
    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

    0 讨论(0)
  • 2021-02-06 21:51

    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.

    0 讨论(0)
  • 2021-02-06 21:51

    try this one..

     Calendar instance = Calendar.getInstance();
     currentMonth = instance.get(Calendar.MONTH);
     currentYear = instance.get(Calendar.YEAR);
    
     int month=currentMonth+1;
    
    0 讨论(0)
提交回复
热议问题