0
public class DateFormat {
    public static void main(String[] args) {

        int year;
        int day;
        int month;
        String format = "";

        System.out.println("Enter a  year: " );
        Scanner scanner = new Scanner(System.in);
        year = scanner.nextInt();
        Scanner scanner2 = new Scanner(System.in);

        System.out.println("Enter a Month: " );
        Scanner scanner1 = new Scanner(System.in);
        month = scanner2.nextInt();
        System.out.println("Enter a Day: ");
        day = scanner1.nextInt();

        System.out.println("Chose Format: (b/l/m) ");
        Scanner scanner3 = new Scanner(System.in);
        format = scanner3.nextLine();
    }
}

I managed to ask ueser for the, day month and year, asks user which formate is prefered and but how can i get the program to display the results in the chosen order?

How to make formulate the code for each option?

And finally how do I make sure any single entred digit like 7 is changed to 07?

These formates are called big-endian, little-endian and middle-endian, yyyy/mm/dd dd/mm/yyyy and even mm/dd/yyyy. I am trying to make the format to be returned as a string from a method that takes the year, month, day and format as input.

domsson
  • 4,553
  • 2
  • 22
  • 40
CyT3
  • 19
  • 3
  • 2
    Just a note: while [Endianness](https://en.wikipedia.org/wiki/Endianness) _can_ be used to describe the order of the segments of a date, in a computer science context, people will pretty much always think of byte order. Also, is this homework? – domsson Jan 18 '20 at 19:24
  • No not homework. – CyT3 Jan 18 '20 at 19:31
  • *"how can i get the program to display the results in the chosen order"* Use a format string that matches the desired order when you **format** the date value. See [Java string to date conversion](https://stackoverflow.com/q/4216745/5221149). Example: `LocalDate.of(year, month, day).format(DateTimeFormatter.ofPattern("dd/MM/uuuu"))` where you use the `b/l/m` value to choose a pattern string. --- Or you can use `printf("%3$02d/%2$02d/%1$04d", year, month, day)`, again using `b/l/m` value to choose the format string. – Andreas Jan 18 '20 at 19:51

1 Answers1

1

As already pointed out by Andreas you should do something like this:

LocalDate date = LocalDate.of(year, month, day);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(getFormatter(format));

System.out.println(date.format(dtf));
private static String getFormatter(String format) {
    switch (format){
        case "b":
             return "yyyy/MM/dd";
        case "l":
           return "dd/MM/yyyy";
        case "m":
            return "MM/dd/yyyy";
    }
    throw new IllegalArgumentException("wrong format choosen: " + format);
}

Bear in mind that the input could be invalid like -1, or 35