从android中的日期选择器和时间选择器投射和获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2592499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:27:59  来源:igfitidea点击:

Casting and getting values from date picker and time picker in android

androidandroid-datepickerandroid-timepicker

提问by Rahul Kalidindi

I have a DatePickerand a TimePickerin my app. Can anyone tell me how to get the values of the date and time that are selected??? What i mean to say is, for EditTextwe can declare as

我的应用程序中有一个DatePicker和一个TimePicker。谁能告诉我如何获取所选日期和时间的值???我的意思是,因为EditText我们可以声明为

final EditText name = (EditText) this.findViewById(R.id.nametext);

and we can cast the data of it by using name.getText().toString().

我们可以使用name.getText().toString().

So similarly how can we get the values of DatePicker and TimePicker to a String???

那么类似地,我们如何将 DatePicker 和 TimePicker 的值转换为字符串???

回答by Jim Blackler

DatePicker has

日期选择器有

getYear() 
getMonth() 
getDayOfMonth()

to make a Date object from a DatePicker you'd do new Date(datePicker.getYear() - 1900, datePicker.getMonth(), datePicker.getDayOfMonth());

从 DatePicker 创建一个 Date 对象,你会这样做 new Date(datePicker.getYear() - 1900, datePicker.getMonth(), datePicker.getDayOfMonth());

Note that this constructor was deprecated in API level 1- please refer to andrescanavesi's answerfor a more appropriate way of creating a Date object.

请注意,此构造函数在 API 级别 1 中已弃用- 请参阅 andrescanavesi 的回答以获取更合适的创建 Date 对象的方法。

TimePicker has

时间选择器有

getCurrentHour()
getCurrentMinute()

回答by Andrés Canavesi

I use this:

我用这个:

    /**
 * 
 * @param datePicker
 * @return a java.util.Date
 */
public static java.util.Date getDateFromDatePicket(DatePicker datePicker){
    int day = datePicker.getDayOfMonth();
    int month = datePicker.getMonth();
    int year =  datePicker.getYear();

    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, day);

    return calendar.getTime();
}

回答by Dheeraj Giroti

date=(EditText)findViewById(R.id.date_of_birth_textfield);

date.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 showDialog(DATE_DIALOG_ID);

            }
        });


        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

updateDisplay();

protected Dialog onCreateDialog(int id) {
        switch(id)
        {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                    mDateSetListener,
                    mYear, mMonth, mDay);
}
return null
}

private DatePickerDialog.OnDateSetListener mDateSetListener= new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            System.out.println("calendar view shown.."+view.getCalendarViewShown());
        c.set(Calendar.YEAR, year);
              c.set(Calendar.MONTH, monthOfYear);
              c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
              mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);
                updateDisplay();
           // mMonth = monthOfYear;
           // mDay = dayOfMonth;

        }
    };

private void updateDisplay() {
        date.setText(
                new StringBuilder()
                // Month is 0 `based` so add 1


                .append(mYear).append("-").append(mMonth + 1).append("-").append(mDay).append(""));
        //date.setText(fmtDateAndTime.format(c.getTime()));

}

回答by Sojurn

I'd suggest looking at the DateFormatclass in android. Be careful to import the DateFormat mentioned in the android docs. After that, whatever formatting you want to achieve is really simple. For a basic Aug 12, 2012 you can do this.

我建议查看android中的DateFormat类。小心导入 android 文档中提到的 DateFormat。之后,您想要实现的任何格式都非常简单。对于基本的 2012 年 8 月 12 日,您可以执行此操作。

DatePicker myDatePicker = (DatePicker) findViewById(R.id.mydatepicker);
String selectedDate = DateFormat.getDateInstance().format(myDatePicker.getCalendarView().getDate());

Look at the DateFormatclass to get various other configurations.

查看DateFormat类以获取各种其他配置。

回答by happyhardik

Combined all the answers and made a code snippet out of it.

结合所有答案并从中制作代码片段。

Import datePicker on the top of your class:

在班级顶部导入 datePicker:

import android.widget.DatePicker;

Inside your class declare the following variable:

在您的类中声明以下变量:

private DatePicker dobPicker;

And here is the code to be done in button click event:

这是要在按钮单击事件中完成的代码:

 dobPicker = (DatePicker)findViewById(R.id.dobPicker);
        Integer dobYear = dobPicker.getYear();
        Integer dobMonth = dobPicker.getMonth();
        Integer dobDate = dobPicker.getDayOfMonth();
        StringBuilder sb=new StringBuilder();
        sb.append(dobYear.toString()).append("-").append(dobMonth.toString()).append("-").append(dobDate.toString()).append(" 00:00:00");
        String dobStr=sb.toString();

Where in R.id.dobPicker, dobPicker is your datePicker in the layout xml file. This gives you a string at the end, which could be stored or sent to the server.

在 R.id.dobPicker 中,dobPicker 是布局 xml 文件中的 datePicker。这会在最后为您提供一个字符串,该字符串可以存储或发送到服务器。

回答by Joshua Pinter

getDateTimeFromPickers()

getDateTimeFromPickers()

Simple Method for Getting Date and Time from a DatePicker and a TimePicker

从 DatePicker 和 TimePicker 获取日期和时间的简单方法

Caveat: it uses JodaTime's DateTimeas the return. You can modify it to use whatever you like.

警告:它采用JodaTimeDateTime作为回报。您可以修改它以使用您喜欢的任何内容。

 // Gets the Date and Time from a DatePicker and TimePicker and return a JodaTime DateTime from them, in current timezone.
 //
 private DateTime getDateTimeFromPickers( int DatePickerId, int TimePickerId ) {
     DatePicker dp = (DatePicker) findViewById(DatePickerId);
     TimePicker tp = (TimePicker) findViewById(TimePickerId);

     String year    = Integer.toString(dp.getYear()) ;
     String month   = StringUtils.leftPad( Integer.toString(dp.getMonth() + 1), 2, "0" );
     String day     = StringUtils.leftPad( Integer.toString(dp.getDayOfMonth()), 2, "0" );
     String hour    = StringUtils.leftPad( Integer.toString(tp.getCurrentHour()), 2, "0" );
     String minutes = StringUtils.leftPad( Integer.toString(tp.getCurrentMinute()), 2, "0" );

     String dateTime = year + "-" + month + "-" + day + "T" + hour + ":" + minutes + ":00.000";

     return DateTime.parse(dateTime);
 }

Hope that helps.

希望有帮助。

JP

J.P

回答by Hassi

I would do it as:

我会这样做:

    Calendar calendar = Calendar.getInstance();
    calendar.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(), Tp.getCurrentHour(), Tp.getCurrentMinute());
    DateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    TimeZone gmtTime = TimeZone.getTimeZone("GMT");
    gmtFormat.setTimeZone(gmtTime);
    String mydate = ""+ gmtFormat.format(calendar.getTime());

p.s dp and tp are date pickers and time picker in android.

ps dp 和 tp 是 android 中的日期选择器和时间选择器。

回答by swathi

StringBuilder sb=new StringBuilder();
        sb.append(myYear).append("-").append(myMonth).append("-").append(myDay);
    String str=sb.toString();
    edittext.setText(str);

回答by Imran Athar

Try bellow with Format Ex: 24 December 2014.

试试下面的格式,例如:2014 年 12 月 24 日。

            DatePicker datePicker = (DatePicker) findViewById(R.id.datepicker_inspection);
            SimpleDateFormat df = new SimpleDateFormat("dd MMMM yyyy");
            String inspectiondate = df.format(new Date(datePicker.getYear() - 1900, datePicker.getMonth(), datePicker.getDayOfMonth()));