Android CalendarView: How do I get the date in correct format?

前端 未结 4 862
我在风中等你
我在风中等你 2021-01-20 18:26

The past few days I\'ve been searching for ways to get a \'readable\' date out of my calendarview from android 4.0. I can\'t manage to find a solution or example that suits

相关标签:
4条回答
  • 2021-01-20 18:48

    You should use SimpleDateFormat

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String selectedDate = sdf.format(new Date(calendar.getDate()));
    
    0 讨论(0)
  • 2021-01-20 19:00

    Okay so here is how to do this. When you fire your calendarview activity or a calendarview inside your activity it sets the date to the current date(meaning today). To get this current date just use the Calendar object provided by the java api to get this date example below:

    Calendar date = Calendar.getInstance();
    // for your date format use
    SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
    // set a string to format your current date
    String curDate = sdf.format(date.getTime());
    // print the date in your log cat
    Log.d("CUR_DATE", curDate);
    

    to get a date changed you must do this

    CalendarView myCalendar = (CalendarView) findViewById(R.id.myCalenderid);
    
    myCalendar.setOnDateChangeListener(myCalendarListener);
    
    OnDateChangeListener myCalendarListener = new OnDateChangeListener(){
    
    public void onSelectedDayChange(CalendarView view, int year, int month, int day){
    
       // add one because month starts at 0
       month = month + 1;
       // output to log cat **not sure how to format year to two places here**
       String newDate = year+"-"+month+"-"+day;
       Log.d("NEW_DATE", newDate);
    }
    }
    
    0 讨论(0)
  • 2021-01-20 19:01

    kandroidj's answer helps to create date, but not date of correct format. So to format selected date:

    calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
    
            @Override
        public void onSelectedDayChange(CalendarView view, int year, int month,
                                        int dayOfMonth) {
            final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month, dayOfMonth);
            String sDate = sdf.format(calendar.getTime());
            Log.d(TAG, "sDate formatted: " + sDate);
        }
    });
    
    0 讨论(0)
  • 2021-01-20 19:10
    long date = calenderView.getDate();
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(date);
    int Year = calendar.get(Calendar.YEAR);
    int Month = calendar.get(Calendar.MONTH);
    int Day = calendar.get(Calendar.DAY_OF_MONTH);
    //customize According to Your requirement
    String finalDate=Year+"/"+Month+"/"+Day;
    
    0 讨论(0)
提交回复
热议问题