I want to get the day of the week from a date
in Java
. Why would this return Friday when
it is, in fact, Tuesday
?
new java.text.SimpleDateFormat("EEEE").format(new java.util.Date(2015, 6, 9))
PS I know java.util.Date(int year, int month, int day)
is deprecated, maybe that has something to do with it.
The month
argument in that deprecated constructor starts at 0
for January, so you probably wanted new Date(115, 5, 9)
if you're talking about June 9th (the 115
is because the year
argument is "since 1900").
From the documentation:
Parameters:
year
- the year minus 1900.
month
- the month between 0-11.
date
- the day of the month between 1-31.
(My emphasis.)
You've said you want to do this as a one-liner. In Java 8, you could do:
String day = LocalDate.of(2015, 6, 9).format(DateTimeFormatter.ofPattern("EEEE"));
that uses java.time.LocalDate
and java.time.format.DateTimeFormatter
.