如何在Android Sqlite中添加日期和时间

时间:2017-12-18 04:41:11

标签: android sqlite

手动安装Android日期和时间选择器并插入sqlite数据库。

  • 日期选择器

  • 时间选择器

1 个答案:

答案 0 :(得分:1)

You should have searched a bit before posting here, anyway if it helps,

private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMinute;
private Calendar mCalendar;

 private void datePicker() {
    mCalendar = Calendar.getInstance();

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

    DatePickerDialog datePickerDialog = new DatePickerDialog(this,
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                    mCalendar.set(Calendar.YEAR, year);
                    mCalendar.set(Calendar.MONTH, monthOfYear);
                    mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                     //here you request timePicker Dialog
                    timePicker();

                }
            }, mYear, mMonth, mDay);
    datePickerDialog.show();

}


private void timePicker() {
    mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
    mMinute = mCalendar.get(Calendar.MINUTE);

    TimePickerDialog mTimePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {

//     here you go, you got selectedHour and selectedMinute, convert them into String
            mCalendar.set(Calendar.HOUR_OF_DAY, selectedHour);
            mCalendar.set(Calendar.MINUTE, selectedMinute);
//                   Now if you want current time in long format 

            long currentTime= mCalendar.getCurrentTimeInMilis();
               // now you can format this to dd-MM using SimpleDateFormat..

System.out.println(formateDate(curentTime));

        }
    }, mHour, mMinute, false);
    mTimePicker.setTitle("Select Time");
    mTimePicker.show();
}

//Conversion to proper date format

 public static String formatDate(long dateInMillis) {
    DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.getDefault());
    Date date = new Date(dateInMillis);
    return dateFormat.format(date);
}

That's it.