1

I have a simple but tricky code to write where I have given the date String of today in UTC time.

String s = Instant.now().toString().replaceAll("T.*", "");

I need to find the first and last days of the last month and store them in separate Strings. Any advice on how to achieve it best?

Arefe
  • 11,321
  • 18
  • 114
  • 168
  • Dont use strings but dates for starters. – Antoniossss Mar 04 '19 at 08:03
  • `LocalDate.now()`? – dehasi Mar 04 '19 at 08:04
  • Please include sample data, and explain why you can't just use now() as suggested, and also expected output. – Joakim Danielson Mar 04 '19 at 08:08
  • @JoakimDanielson I use the `import java.time.*` and don't want to mix up with many libraries. Besides, I need to be careful to know the current `UTC` date and find the first + last date of the last month. Ok, I just find they are indeed in the same library `java.time.LocalDate`. – Arefe Mar 04 '19 at 08:19
  • Indeed, a duplicate... not sure why I don't get that in the Google search. – Arefe Mar 05 '19 at 08:30

4 Answers4

4

You can make use of TemporalAdjusters.

If you don't have to start with a string, don't. Start with a LocalDate if possible.

If you have to start with a string, you can convert your string s to a LocalDate by parse:

LocalDate ld = LocalDate.parse(s);

Now we can get the start and end of the month like this:

LocalDate startOfMonth = ld.with(TemporalAdjusters.firstDayOfMonth());
LocalDate endOfMonth = ld.with(TemporalAdjusters.lastDayOfMonth());

I suggest you not to convert them to strings until the absolutely necessary (like you display it to the user).

Sweeper
  • 213,210
  • 22
  • 193
  • 313
4

You can get using LocalDate

LocalDate startOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
LocalDate endOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
Eklavya
  • 17,618
  • 4
  • 28
  • 57
3

It's quite simple when using LocalDate and its date arithmetic functions:

LocalDate now = LocalDate.now();
LocalDate firstDayOfCurrentMonth = now.withDayOfMonth(1);

LocalDate firstDayOfLastMonth = firstDayOfCurrentMonth.minusMonths(1);
LocalDate lastDayOfLastMonth = firstDayOfCurrentMonth.minusDays(1);
Peter Walser
  • 15,208
  • 4
  • 51
  • 78
2

If you want to get the month before the current date then use the below code:

LocalDate today = LocalDate.now(ZoneOffset.UTC);  // Retrieve the date now
LocalDate lastMonth = today.minus(1, ChronoUnit.MONTHS); // Retrieve the date a month from now
System.out.println("First day: " + lastMonth.withDayOfMonth(1)); // retrieve the first date
System.out.println("Last day: " + lastMonth.withDayOfMonth(lastMonth.lengthOfMonth())); // retrieve the last date
Mark Melgo
  • 1,477
  • 1
  • 13
  • 30