java.time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/u");
String fechaaux = "01/07/2019";
LocalDate date = LocalDate.parse(fechaaux, formatter);
DayOfWeek dayOfWeek = date.getDayOfWeek();
System.out.println("dayOfWeek: " + dayOfWeek);
Output is:
dayOfWeek: MONDAY
You should avoid using SimpleDateFormat
, Date
and Calendar
. While I don’t know what went wrong in your code, those classes are long outdated and poorly designed. Instead I recommend java.time, the modern Java date and time API. It is so much nicer to work with.
But can I add the "date" object, to this?
Sometimes we get an old-fashioned Date
object from an API that we don’t want to upgrade just now. In that case a possible conversion is:
ZonedDateTime zdt
= oldfashionedDate.toInstant().atZone(ZoneId.systemDefault());
DayOfWeek dayOfWeek = zdt.getDayOfWeek();
Edit:
Is much better use Java Date
before than Java Calendar
? The result is
the same?
You should avoid both. Only if you are getting one of them from a legacy API that you cannot change, accept what you get and convert it to a modern type first thing. If you get a Date
, use the conversion above. If you get a Calendar
, you can be about certain that it is a GregorianCalendar
. If so:
ZonedDateTime zdt = ((GregorianCalendar) theCalendarYouGot).toZonedDateTime();
Now proceed as above.
Historically Calendar
and GregorianCalendar
were introduced as a (somewhat failed) attempt to make up for the design problems with Date
.
Link: Oracle tutorial: Date Time explaining how to use java.time.