try {
System.out.println("Please enter a start date and an end date for your stay (dd/mm/yyyy): ");
startDate = sdf.parse(input.next());
endDate = sdf.parse(input.next());
long diff = endDate.getTime() - startDate.getTime();
int diffInt = (int) (diff / (1000 * 60 * 60 * 24));
if (diffInt == 7 || diffInt == 14) {
System.out.println("Your reservation has been successfully booked for "+startDate+" until "+endDate);
break;
}
} catch (ParseException e) {
System.out.println("You have entered an invalid date range. Please try again.");
e.printStackTrace();
} //END OF TRY-CATCH
这是我到目前为止的代码。我正在做的是从用户那里获取两个日期的输入,然后使用这些日期来计算它们之间有多少天。如果他们选择的两个日期之间有7天或14天,则说明成功。
到目前为止,它运行良好,但唯一的问题是何时执行以下行:
System.out.println("Your reservation has been successfully booked for "+startDate+" until "+endDate);
break;
当它打印出变量时,它会打印出日期和我不想要的“ 00:00:00 GMT”。
老实说,我不喜欢它如何打印“ Tue Jan 01 00:00:00 GMT”之类的日期,这也不是一件好事。我希望它看起来如何输入,例如01/01/2019。
任何帮助表示赞赏。
您想看一下SimpleDateFormat。
SimpleDateFormat
使用所需的输出格式实例化a ,new SimpleDateFormat("dd/MM/yyyy")
然后简单地使用该format(java.util.Date)
方法将日期对象转换为所需格式的字符串。在上面的代码示例中,这可能会为您提供所需的输出:
...
DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy");
String startDateString = outputFormat.format(startDate);
String endDateString = outputFormat.format(endDate);
System.out.println("Your reservation has been successfully booked for "+startDateString+" until "+endDateString);
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句