-1

Im working on a project that visually displays statistical data from each month and week and i dont know how to elegantly renew the dates of each week and month.

For example, i want to display this months data. I have to make two date variables in Java. The first one being 1.5.2021 and the second one being todays date. I dont know how to elegantly set the first variable to 1.x.xxxx without making a string out of the current date first and then cuting it, doing some numerics with it and merging it back together to 1.5.2021.

Same goes for weekly statistics where i need the Monday date and the Sunday date, for example today being Monday 10.5.2021 and the end on 17.5.2021.

So my idea is to get current date to string format, slice it, convert it to int, calculate the desired dates and the put it back to string(no need to go back to datetype since its gonna be used for querying).

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Kalybor
  • 51
  • 8

1 Answers1

1

Well, you should definitely take a look at the classes within the java.time package.

In your case, your current date could be a LocalDate instance, for example with the following line:

LocalDate.of(2021, 5, 1);

And then you could just use the withDayOfMonth method to get a new LocalDate instance with the day of the month set to 1:

LocalDate currentDate = LocalDate.now();
LocalDate firstOfMonth = currentDate.withDayOfMonth(1);
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • Yes i can use this for the month part. I'll check java.time package if similar thing can be done to get the mondays date of the current week. – Kalybor May 10 '21 at 11:40
  • @Kalybor Well, this can be done with a [`TemporalAdjuster`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/time/temporal/TemporalAdjuster.html), which is able to convert some temporal to another one based on some logic. The [`TemporalAdjusters`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/time/temporal/TemporalAdjusters.html) helper class contains a set of methods with commonly used adjustments, such as finding the Monday before the current date. Something like `currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)` would do the trick. – MC Emperor May 10 '21 at 12:18
  • If your week goes from Monday to Sunday always (you don’t need to take into account that the week may start on Sunday or some other day of the week), then just `currentDate.with(DayOfWeek.MONDAY)` and similarly for Sunday. – Ole V.V. May 10 '21 at 12:31
  • Thank you very much, both replies are valid. Worked wonderful. – Kalybor May 11 '21 at 07:10