我目前正在根据入住和退房日期对计算假期成本的应用进行原型设计。这个想法是,一旦提交日期,While循环就会一直运行,直到达到结账日期。但是,我似乎无法正确解析日历日期。在最近的测试中,我输入了2015年2月20日的支票,并于2015年2月22日退房,两者在logcat中都记录为1-2-5。
以下是我正在处理的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection);
Button btnSubmit = (Button) findViewById(R.id.btnSubmit);
final DatePicker datePickerCheckIn = (DatePicker) findViewById(R.id.datePickerCheckIn);
final DatePicker datePickerCheckOut = (DatePicker) findViewById(R.id.datePickerCheckOut);
final TextView studioTotal = (TextView) findViewById(R.id.studioTotal);
final TextView oneBedTotal = (TextView) findViewById(R.id.oneBedTotal);
final TextView twoBedTotal = (TextView) findViewById(R.id.twoBedTotal);
final TextView villaTotal = (TextView) findViewById(R.id.villaTotal);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
//Set check in values
int checkInDay = datePickerCheckIn.getDayOfMonth();
int checkInMonth = datePickerCheckIn.getMonth();
checkInMonth = checkInMonth + 1;
int checkInYear = datePickerCheckIn.getYear();
//Set check out values
int checkOutDay = datePickerCheckOut.getDayOfMonth();
int checkOutMonth = datePickerCheckOut.getMonth();
checkOutMonth = checkOutMonth + 1;
int checkOutYear = datePickerCheckOut.getYear();
//Reset rates
studioTotalPoints = 0;
oneBedTotalPoints = 0;
twoBedTotalPoints = 0;
villaTotalPoints = 0;
final String checkInStart = checkInYear+"-"+checkInMonth+"-"+checkInDay;
final String checkOutEnd = checkOutYear+"-"+checkOutMonth+"-"+checkOutDay;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar dateStart = Calendar.getInstance();
try {
dateStart.setTime(sdf.parse(checkInStart));
} catch (ParseException e) {
e.printStackTrace();
}
Calendar dateEnd = Calendar.getInstance();
try {
dateEnd.setTime(sdf.parse(checkOutEnd));
} catch (ParseException e) {
e.printStackTrace();
}
Log.i("Start Date: ", dateStart.YEAR+"-"+dateStart.MONTH+"-"+dateStart.DAY_OF_MONTH);
Log.i("End Date: ", dateEnd.YEAR+"-"+dateEnd.MONTH+"-"+dateEnd.DAY_OF_MONTH);
while (dateStart.DAY_OF_YEAR < dateEnd.DAY_OF_YEAR)
{
studioTotalPoints += rateStudioA1;
oneBedTotalPoints += rate1BedA1;
twoBedTotalPoints += rate2BedA1;
villaTotalPoints += rateVillaA1;
dateStart.add(Calendar.DATE, 1);
Log.i("Dates", dateStart+"-"+dateEnd);
totalNights +=1;
}
studioTotal.setText(""+studioTotalPoints);
oneBedTotal.setText(""+oneBedTotalPoints);
twoBedTotal.setText(""+twoBedTotalPoints);
villaTotal.setText(""+villaTotalPoints);
}
};
btnSubmit.setOnClickListener(listener);
}
日期从日期选择器到日历的解析方式似乎有问题,但我不确定它是什么。
有人有任何建议吗?
答案 0 :(得分:0)
尝试这样做:
String checkInStart = checkInYear+"-"+checkInMonth+"-"+checkInDay;
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate;
try {
startDate = sdf.parse(checkInStart);
String newDateString = sdf.format(startDate);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
正确解析字符串。