Why does Java make it not obvious how to get the day of the month from a Date object?
.getDay() was deprecated, it is recommended to use Calendar.get(Calendar.MONTH)
This makes little sense to me and I was curious what the rationale behind this deprecation is.
I have a Date object and I just want the day. It’s the most natural thing ever and I can’t invoke it. This design is wrong and therefore my code is not working the way it should:
private String getIngivningsDag() {
return ""+ingivningsDatum.getDate();
}
private String getIngivningsMonth() {
return ""+ingivningsDatum.getmonth();
}
private String getIngivningsYear() {
return ""+ingivningsDatum.getYear();
}
Update
here’s the “solution”:
public String getIngivningsDag() {
Calendar cal = Calendar.getInstance();
cal.setTime(ingivningsDatum);
return cal.get(Calendar.DAY_OF_WEEK_IN_MONTH)+"";
}
Here’s how it should look simple and good without the design errors of Java and using method parameters instead of strange Class methods and factories:
public String getIngivningsDag() {
return ingivningsDatum.getDay(Calendar.GREGORIAN, "SE");
}
Not only that method, most of the methods of
Dateclass and some constructors are now deprecated. You have to useCalendarclass to getDAY, orMONTHfrom your Date object.However, I would suggest you to try out
Joda-Time API, that will make you much more happier, because, evenCalendarclass is abit inconsistentwhen it comes to indexing ofMONTH, which starts from0in it.But, still, as for your current problem, you can convert your
Dateobject to aCalendarinstance using: –