-1

I need to check that 04/07/19 is exactly Sun, 7 Apr. This assertion is used in one of my tests.

Vadam
  • 85
  • 1
  • 4
  • did you mean you want to check that on 7th Apr, 2019 it is Sunday or not? – jmj Mar 18 '19 at 22:03
  • Welcome to Stack Overflow. This question has been asked and answered with variations very many times before. Do yourself the favour of searching before posting a question. You will get an answer faster and you will get the best answers (not that the ones already posted here are bad). – Ole V.V. Mar 19 '19 at 07:39

3 Answers3

2

You can use DateTimeFormatter to parse a String to LocalDate and format it back again to a String:

// create a date from the String input
LocalDate date = LocalDate.parse("04/07/19", DateTimeFormatter.ofPattern("MM/dd/yy", Locale.ENGLISH));
// format the date back to a new string
String result = date.format(DateTimeFormatter.ofPattern("EE, d MMM", Locale.ENGLISH));
System.out.println(result);

The result is: Sun, 7 Apr

If you want to use another Language you can just change the Locale parameter. The default is your system language.

To understand or change date format patterns this reference might help. It describes all the different symbols and meanings.

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
1
private void go() {
    String date = "04/07/19";

    DateTimeFormatter fromFormatter = DateTimeFormatter.ofPattern("MM/dd/yy");
    DateTimeFormatter toFormatter = DateTimeFormatter.ofPattern("EEE, d MMM");

    System.out.println(toFormatter.format(fromFormatter.parse(date)));
}

Yields Sun, 7 Apr

Not a JD
  • 1,864
  • 6
  • 14
1

You can use the LocalDate class (available since java 8) with a DateTimeFormatter. This is an example:

public static void main(String... args) {
        LocalDate date = LocalDate.parse("04/07/19",DateTimeFormatter.ofPattern("MM/dd/yy"));
        System.out.println( date.format(DateTimeFormatter.ofPattern("EEE, d MMM")));
        //If you need the day of the week
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        System.out.println("Day of week : "+dayOfWeek);
    }

It'll print :

Sun, 7 Apr

Day of week : SUNDAY

Hope this can help you

Marcos Echagüe
  • 547
  • 2
  • 8
  • 21