Ravindu
Ravindu

Reputation: 2550

How can I get selected date in CalenderView in Android?

Calendar date = Calendar.getInstance();     
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");

curDate = sdf.format(date.getTime());

I have done the above code inside onCreate method. But it can only return the current date. What I want is to have the date selected in the calender.

<CalendarView
      android:id="@+id/calendarView1"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

Please help me

Upvotes: 5

Views: 42517

Answers (5)

Rahul Raina
Rahul Raina

Reputation: 3460

Example code in Kotlin to fetch selected date in CalenderView:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <CalendarView
        android:id="@+id/calendar_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Toast Selected Date" />

</LinearLayout>

MainActivity.kt

import android.os.Bundle
import android.text.format.DateFormat
import android.util.Log
import android.widget.CalendarView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.testandcheck.databinding.ActivityMainBinding
import java.util.*

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding   // Binding object for ViewBinding.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    // Set date change listener on calenderView.
    // Callback notified when user select a date from CalenderView on UI.
    binding.calendarView.setOnDateChangeListener { calView: CalendarView, year: Int, month: Int, dayOfMonth: Int ->

        // Create calender object with which will have system date time.
        val calender: Calendar = Calendar.getInstance()

        // Set attributes in calender object as per selected date.
        calender.set(year, month, dayOfMonth)

        // Now set calenderView with this calender object to highlight selected date on UI.
        calView.setDate(calender.timeInMillis, true, true)
        Log.d("SelectedDate", "$dayOfMonth/${month + 1}/$year")
    }

    // Example button to show get selected date from CalenderView and show in Toast.
    binding.button.setOnClickListener {

        // Fetch long milliseconds from calenderView.
        val dateMillis: Long = binding.calendarView.date

        // Create Date object from milliseconds.
        val date: Date = Date(dateMillis)

        // Get Date values and created formatted string date to show in Toast.
        val selectedDayOfWeek = DateFormat.format("EEEE", date) as String // Monday
        val selectedDay = DateFormat.format("dd", date) as String // 05
        val selectedMonthString = DateFormat.format("MMM", date) as String // Jul
        val selectedMonthNumber = DateFormat.format("MM", date) as String // 6 --> Month Code as Jan = 0 till Dec = 11.
        val selectedYear = DateFormat.format("yyyy", date) as String // 2021

        val strFormattedSelectedDate = "$selectedDay-${selectedMonthNumber + 1}-$selectedYear ($selectedDayOfWeek)"
        Toast.makeText(applicationContext, "Selected Date = $strFormattedSelectedDate", Toast.LENGTH_SHORT).show()
    }
}

}

Explaination:

  1. Set listener to set selected date in CalenderView (also highlight the newly selected date and un-highlight the older date).
  2. Then only call calenderView.date to get selected date.

Upvotes: 2

Kavindu Dissanayake
Kavindu Dissanayake

Reputation: 895

You can get Selected date using Calendar view Like this...

CalendarView calendarView=view.findViewById(R.id.calendarView);

    calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {

        @Override
        public void onSelectedDayChange(CalendarView view, int year, int month,
                                        int dayOfMonth) {
          String  curDate = String.valueOf(dayOfMonth);
          String  Year = String.valueOf(year);
          String  Month = String.valueOf(month);

            Log.e("date",Year+"/"+Month+"/"+curDate);
        }
    });

Upvotes: 1

Ravindu
Ravindu

Reputation: 2550

I used CalendarView instead of Calender and it's working now.

calendarView.setOnDateChangeListener(new OnDateChangeListener() {

                @Override
                public void onSelectedDayChange(CalendarView view, int year, int month,
                        int dayOfMonth) {
                    curDate = String.valueOf(dayOfMonth);
                }
            });

Upvotes: 17

Jevgenij Kononov
Jevgenij Kononov

Reputation: 1237

    final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    final DateFormat dateFormat_year = new SimpleDateFormat("yyyy");
    final DateFormat dateFormat_month = new SimpleDateFormat("MM");
    final DateFormat dateFormat_day = new SimpleDateFormat("dd");
    Calendar cal = Calendar.getInstance();

    System.out.println(dateFormat.format(cal.getTime()));
    System.out.println(dateFormat_year.format(cal.getTime()));
    System.out.println(dateFormat_month.format(cal.getTime()));
    System.out.println(dateFormat_day.format(cal.getTime()));

Upvotes: -2

Hassan Mokdad
Hassan Mokdad

Reputation: 5902

Did you try Calendar.get(Calendar.DATE)

Check the link GetDate() Calendar

Upvotes: -1

Related Questions