MainActivity
package com.example.wuzuo.timedemo; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.CalendarView; import android.widget.DatePicker; import android.widget.TimePicker; import java.util.Calendar; public class MainActivity extends AppCompatActivity { private DatePicker datePicker; private TimePicker timePicker; private Calendar calendar; private int year; private int Month; private int Day; private int Hour; private int Minute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); calendar=Calendar.getInstance(); year=calendar.get(Calendar.YEAR); Month=calendar.get(Calendar.MONTH)+1; Day=calendar.get(Calendar.DAY_OF_MONTH); Hour=calendar.get(Calendar.HOUR_OF_DAY); Minute=calendar.get(Calendar.MINUTE); datePicker= (DatePicker) findViewById(R.id.datePicker1); timePicker= (TimePicker) findViewById(R.id.timePicker1); setTitle(year + "-" + Month + "-" + Day + " " + Hour + ":" + Minute); datePicker.init(year, calendar.get(Calendar.MONTH), Day, new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setTitle(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth); } }); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { setTitle(hourOfDay + ":" + minute); } }); new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setTitle(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth); } }, year, calendar.get(Calendar.DAY_OF_MONTH), Day).show(); new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { setTitle(hourOfDay + ":" + minute); } }, Hour, Minute, true).show(); } }activity_main
<?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" > <DatePicker android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="3" android:id="@+id/datePicker1" /> <TimePicker android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="5" android:id="@+id/timePicker1" /> </LinearLayout>