如何在不打印 Java 中的时间的情况下打印日期?

How do I print a date without also printing the time in Java?

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" 这样打印日期的方式,这也不太好。我宁愿它看看它是如何输入的,例如2019 年 1 月 1 日。

感谢任何帮助。

您想看SimpleDateFormat

使用所需的输出格式实例化自己 SimpleDateFormat,例如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);
...