如何根据 android 中的另一个日期获取未来日期?
How to get future date based on another date in android?
我想通过日期选择器对话框选择日期,基于此我需要在 20 天后获取日期。例如:如果我选择 2-5-2021,需要得到 22-5-2021.But 我得到了 parseException。如何实现?
我的代码是,
Calendar calendar = Calendar.getInstance();
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yyyy").parse(transactionDate.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 20);
Toast.makeText(this, (CharSequence) calendar.getTime(), Toast.LENGTH_SHORT).show();
使用此函数并传递参数作为您的当前日期和您要添加的天数 (20)。
public static String getCalculatedDate(String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
cal.add(Calendar.DAY_OF_YEAR, days);
return s.format(new Date(cal.getTimeInMillis()));
}
找到解决方案:
public void getCalculatedDate() {
try {
String date = selectedDate.getText().toString();
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Date parseDate = format.parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(parseDate);
cal.add(Calendar.DAY_OF_MONTH, 20);
newDate.setText(format.format(cal.getTime()));
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
注意: 从日期选择器对话框中获取的 selectedDate。
我想通过日期选择器对话框选择日期,基于此我需要在 20 天后获取日期。例如:如果我选择 2-5-2021,需要得到 22-5-2021.But 我得到了 parseException。如何实现?
我的代码是,
Calendar calendar = Calendar.getInstance();
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yyyy").parse(transactionDate.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 20);
Toast.makeText(this, (CharSequence) calendar.getTime(), Toast.LENGTH_SHORT).show();
使用此函数并传递参数作为您的当前日期和您要添加的天数 (20)。
public static String getCalculatedDate(String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
cal.add(Calendar.DAY_OF_YEAR, days);
return s.format(new Date(cal.getTimeInMillis()));
}
找到解决方案:
public void getCalculatedDate() {
try {
String date = selectedDate.getText().toString();
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Date parseDate = format.parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(parseDate);
cal.add(Calendar.DAY_OF_MONTH, 20);
newDate.setText(format.format(cal.getTime()));
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
注意: 从日期选择器对话框中获取的 selectedDate。