Blackbath
Blackbath

Reputation: 19

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

This is the code I have so far. What I am doing is getting input for two dates from the user, then using those dates to figure out how many days there are between them. If there are either 7 or 14 days between the two dates they have selected, then it is successful.

It works well so far but the only problem is when this line is executed:

System.out.println("Your reservation has been successfully booked for "+startDate+" until "+endDate);
            break;

When it prints out the variables, it prints out the date plus "00:00:00 GMT" which I don't want.

To be honest I don't like how it prints out the date like "Tue Jan 01 00:00:00 GMT" which isn't great either. I would rather it look how it's input e.g. 01/01/2019.

Any help is appreciated.

Upvotes: 0

Views: 833

Answers (1)

John Stringer
John Stringer

Reputation: 587

You want to look at SimpleDateFormat.

Instantiate yourself a SimpleDateFormat with the desired output format e.g. new SimpleDateFormat("dd/MM/yyyy") and then simply use the format(java.util.Date) method to convert your date objects to strings in your desired format. In your code example above this would probably get you your desired output:

...
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);
...

Upvotes: 3

Related Questions