使用DatePicker以及TimePicker显示当前日期和时间

package com.example.datetimepicker;


import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;


public class MainActivity extends Activity {
	private TimePicker timepicker;
	private DatePicker datepicker;
	private Calendar cal;
	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.main);
        //获取日历的一个对象
        cal=Calendar.getInstance();
        //获取年月日时分秒的信息
        year=cal.get(Calendar.YEAR);
        month=cal.get(Calendar.MONTH)+1;//一月是从0开始计算的,所以要+1
        day=cal.get(Calendar.DAY_OF_MONTH);
        hour=cal.get(Calendar.HOUR_OF_DAY);
        minute=cal.get(Calendar.MINUTE);
        setTitle(year+"-"+month+"-"+day+"-"+hour+":"+minute);
        datepicker=(DatePicker) findViewById(R.id.datePicker);
        timepicker=(TimePicker) findViewById(R.id.timePicker);
        
        //datepicker初始化
        datepicker.init(year,cal.get(Calendar.MONTH),day,new OnDateChangedListener() {
			
			@Override
			public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				// TODO Auto-generated method stub
		        setTitle(year+"-"+(month)+1+"-"+day+"-"+hour+":"+minute);
			}
		});
        timepicker.setOnTimeChangedListener(new OnTimeChangedListener() {
			
			@Override
			public void onTimeChanged(TimePicker view, int hourofday, int minute) {
				// TODO Auto-generated method stub
				setTitle(hourofday+":"+minute);
			}
		});
        new DatePickerDialog(this, new OnDateSetListener() {
			
			@Override
			public void onDateSet(DatePicker view, int year, int monthofyear, int dayofmonth) {
				// TODO Auto-generated method stub
		        setTitle(year+"-"+(monthofyear+1)+"-"+dayofmonth);

			}
		}, year, cal.get(Calendar.MONTH), day).show();//对话框显示
        
        new TimePickerDialog(this, new OnTimeSetListener() {
			
			@Override
			public void onTimeSet(TimePicker arg0, int hourofday, int minute) {
				// TODO Auto-generated method stub
				setTitle(hourofday+":"+minute);
			}
		}, hour, minute, true).show();
        
        
    }
}

你可能感兴趣的:(Android)