问题:
This question already has an answer here:
How to get the first date and last date of the previous month? (Java) 7 answers
I have a simple but trick...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
This question already has an answer here:
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?
回答1:
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
回答2:
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).
回答3:
You can get using LocalDate
LocalDate startOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
LocalDate endOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
回答4:
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);