嘿伙计们我正在开发一个可用于预测婴儿出生日期的应用程序,但我未能弄清楚如何从下面的日期时间选择器对话框增加日期是我的代码
public class Dday extends Activity implements OnClickListener{
private EditText fromDateEtxt;
private DatePickerDialog fromDatePickerDialog;
private SimpleDateFormat dateFormatter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dday);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
findViewsById();
setDateTimeField();
}
private void findViewsById() {
fromDateEtxt = (EditText) findViewById(R.id.etxt_fromdate);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
}
private void setDateTimeField() {
fromDateEtxt.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dday, menu);
return true;
}
public void showDate (View view)
{
// Adding the days to the date
// Button action
Intent dts = new Intent(this,Details.class);
startActivity(dts);
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
if(view == fromDateEtxt) {
fromDatePickerDialog.show();
}
}
答案 0 :(得分:0)
您可以使用以下内容将Calendar对象增加39周:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, 39);
答案 1 :(得分:0)
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
Calendar c = Calendar.getInstance();
c.set(selectedYear, selectedMonth, selectedDay);
c.add(Calendar.DATE, 39);
}
了解更多信息,请参阅此帖子How do I set the date for a date picker?
答案 2 :(得分:0)
您可以使用日历对象并从今天创建日期,并使用日历类添加39周,方法是根据日历和修改后的日历设置日期对象,如下所示:
// Formatter for readable comparison
DateFormat sdf = new SimpleDateFormat("MM dd yyyy", Locale.getDefault());
// Today
Calendar now = Calendar.getInstance();
Date dateToday = new Date();
dateToday.setTime(now.getTimeInMillis());
// 39 weeks from today
Date futureDate = new Date();
// Calendar supports roll over with year so no need to worry about modifying year separate
now.add(Calendar.WEEK_OF_YEAR, 39);
futureDate.setTime(now.getTimeInMillis());
// Print out for comparison
System.out.println(sdf.format(dateToday));
System.out.println(sdf.format(futureDate));
打印出来:
I/System.out﹕ 09 16 2015 <-- Today
I/System.out﹕ 06 15 2016 <-- 39 weeks later