最近做项目遇到一个需求那就是 用户点击日历按钮选择日期查询相关的数据,由于向服务器提交的日期数据格式为XXXX-XX-XX格式 ,但是Calendar点击之后获到的格式却不同, Calendar的月份或者日期如果是单数的话那就是一个数字例如:2019-1-1 而服务器需要的是2019-01-01这种格式 最后自己写了一个方法 转化了一下 写个文章记录一下 由于是android初学者 如有菜鸡操作还请各位大佬指点指点;
第一种方法(复制粘贴直接用):
//打开日历
private void rq() {
Calendar calendar = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
//转化为XXXX-XX-XX格式 创建一个全局变量接收一下处理过后的值,这里我创建了一个类型为String的变量 dad0 。
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String smonth = String.valueOf(month);
String sdayofmonth = String.valueOf(dayOfMonth);
if (smonth.length() == 1 && sdayofmonth.length() == 1) {
txt_rwrq.setText(String.format("%d-%d-%d", year, month + 1, dayOfMonth));
dad0 = String.format("%d-0%d-0%d", year, month + 1, dayOfMonth);
Log.e("sda1", dad0);
return;
}
if (smonth.length() == 1) {
txt_rwrq.setText(String.format("%d-%d-%d", year, month + 1, dayOfMonth));
dad0 = String.format("%d-0%d-%d", year, month + 1, dayOfMonth);
Log.e("sda2", dad0);
return;
}
if (sdayofmonth.length() == 1) {
txt_rwrq.setText(String.format("%d-%d-%d", year, month + 1, dayOfMonth));
dad0 = String.format("%d-%d-0%d", year, month + 1, dayOfMonth);
Log.e("sda3", dad0);
return;
}
if (smonth.length() != 1 && sdayofmonth.length() != 1) {
txt_rwrq.setText(String.format("%d-%d-%d", year, month + 1, dayOfMonth));
dad0 = String.format("%d-%d-%d", year, month + 1, dayOfMonth);
Log.e("sda3", dad0);
return;
}
}
第二种方法(复制粘贴直接用):
//打开日历
private void rq() {
Calendar calendar = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
//转化为XXXX-XX-XX格式
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
dad0 = getDate(year, month, dayOfMonth);
Log.i(TAG, "onDateSetdad0: " + dad0);
}
//转化为XXXX-XX-XX格式
private String getDate(int year, int month, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth);
return DateFormat.format("yyyy-MM-dd", calendar).toString();
}