find first and last date of the last month [duplicate]

问题: 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);
  • 发表于 2019-03-05 18:19
  • 阅读 ( 202 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除