Why does new java.text.SimpleDateFormat("EEEE").format(new java.util.Date(2015, 6, 9)) return the wrong day of the week?

327 views Asked by At

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.

2

There are 2 answers

18
T.J. Crowder On BEST ANSWER

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.

0
Arvind Kumar Avinash On

java.time

The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.

Solution using modern date-time API:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;

public class Main {
    public static void main(String args[]) {
        System.out.println(DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH).format(LocalDate.of(2015, 6, 9)));

        // Alternatively
        System.out.println(LocalDate.of(2015, 6, 9).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH));
    }
}

Output:

Tuesday
Tuesday

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.