I was recently doing a question on HackerRank in which I was asked to find the day on a given date. I used SimpleDateFormat
to find the day.
Below is my code:
String sd = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year);
try {
Date d = new SimpleDateFormat("DD-MM-yyyy").parse(sd);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
return sdf.format(d).toUpperCase();
} catch (Exception e) {
return "";
}
The funny thing here is that the above code is printing correct result for today's date i.e. 03/04/2020(Friday
) but it is returning incorrect day on 05/08/2015(it should return Wednesday
but instead it returns Monday
).
Please help me to find the problem.
Thank you.
EDIT
I was doing a little mistake that I wanted to use the day of the month, for which dd
has to be used. DD
represents the day of the year. That solved my problem!
You should be using SimpleDateFormat("dd-MM-yyyy")
.
DD is for day in year, like there are 365 days in a year.