Android中对时间的各类操作

来源:互联网 发布:贵阳广电网络公司地址 编辑:程序博客网 时间:2024/05/14 18:05

1.在日期字符串中提取年月日(2000-01-01中得到2000,01,01)

  1. try {  
  2.             Calendar cal = Calendar.getInstance();  
  3.             cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse("2000-01-01"));  
  4.             System.out.println(cal.get(Calendar.YEAR));  
  5.             System.out.println(cal.get(Calendar.MONTH)+1);  
  6.             System.out.println(cal.get(Calendar.DAY_OF_MONTH));  
  7.         } catch (ParseException e) {  
  8.             e.printStackTrace();  
  9.         }
try {    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");    Date date = sdf.parse("2000-01-01");    mYear = date.getYear()+1900;    mMonth = date.getMonth() ;    mDay = date.getDate();} catch (ParseException e) {    e.printStackTrace();}

2.Android 中时间控件的使用

private void showDateDialog() {    // 点击"日期"按钮布局 设置日期            DatePickerDialog dpd=new DatePickerDialog(_context,                    new DatePickerDialog.OnDateSetListener() {                        @Override                        public void onDateSet(DatePicker view, int year,                                              int month, int day) {                            // TODO Auto-generated method stub                            mYear = year;                            mMonth = month;                            mDay = day;                            // 更新EditText控件日期 小于10加0                            _tv_date.setText(new StringBuilder()                                    .append(mYear)                                    .append("-")                                    .append((mMonth + 1) < 10 ? "0"                                            + (mMonth + 1) : (mMonth + 1))                                    .append("-")                                    .append((mDay < 10) ? "0" + mDay : mDay));                            String trim = _tv_date.getText().toString().trim();                            if (trim!=null && !trim.equals("")){                                changeUser("birthday",trim);//接口上传到服务器                            }                        }                    }, calendar.get(Calendar.YEAR), calendar                    .get(Calendar.MONTH), calendar                    .get(Calendar.DAY_OF_MONTH));    if (mYear!=0) {        dpd.updateDate(mYear, mMonth, mDay);//再次弹出时间选择器时定位到上次选择的位置    }    dpd.getDatePicker().setMaxDate(System.currentTimeMillis());//设置最大日期不能超过当天    dpd.show();}

0 0
原创粉丝点击