Reputation: 25
I just started learning Java, and I am having extremely hard time, it just seems so complicated compared to C. I have to write a program that detects the current day of the week, and then finds all the remaining same days until specific date. It has to be printed out by the month. So let say its 2016/3/9 now, its Wednesday. The specific date is 2016/4/8. It should print out: 2016/3: 16, 23, 30 2016/4: 6
I am supposed to use java.util.date and java.util.calendar and similar. Thanks for your answers.
Upvotes: 0
Views: 340
Reputation: 338316
FYI, the java.util.Date/.Calendar classes are terrible. While well-intentioned, they are poorly designed, confusing, and troublesome. So do not judge Java or your learning by these classes. Indeed, avoid using these classes altogether.
The old classes are so bad that Sun/Oracle gave up on them, supplanting them with new classes in the java.time framework. The java.time framework is built into Java 8 and later. See Tutorial.
LocalDate
classYou want the LocalDate
class to represent a date-only without time-of-day and without time zone.
You can instantiate a LocalDate
by parsing a string or specifying the numbers of the year, month, and day.
LocalDate localDate = LocalDate.parse( "2016-04-08" );
LocalDate localDate = LocalDate.of( 2016 , 4 , 8 );
Note that determining 'today' requires a time zone even though the resulting LocalDate
stores no time zone internally. For any given moment, the date may vary around the world by time zone. A new day dawns earlier in Paris than in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
Add a week to get the next date with the same day-of-week.
LocalDate next = today.plusWeeks( 1 );
LocalDate
Compare LocalDate
objects with the isBefore
, isAfter
, and isEqual
methods.
I will let you put that together to complete your homework assignment.
Also, you can ask a LocalDate
for a DayOfWeek
object. That object has handy methods such as getDisplayName
for a localized name of the day-of-week.
Upvotes: 4