How to get the time of last week's Monday and Sunday using LocalDate in JAVA
扔个三星炸死你
扔个三星炸死你 2017-06-23 09:13:25
0
4
1010

As in the title, for example, today is 2017.6.21. How do I get the Monday of last week 2017-06-12

扔个三星炸死你
扔个三星炸死你

reply all(4)
为情所困

Thanks for the invitation.

I remember that there seemed to be some problem with Java's Date processing, but I forgot the details. Generally, the enterprise-level Time framework Joda-Time is used, for example:

//今天
DateTime today = DateTime.now();
//上周的今天
DateTime sameDayLastWeek = today.minusWeeks(1);
//上周的周一
DateTime mondayLastWeek = sameDayLastWeek.withDayOfWeek(DateTimeConstants.MONDAY);
//上周的周日
DateTime sundayLastWeek = sameDayLastWeek.withDayOfWeek(DateTimeConstants.SUNDAY);
阿神

As for the problem with Java's Date processing, it was the old java.util.Date. The API processing time of the new package java.time is also very convenient. The API refers to many excellent Time Frameworks, such as Joda-Time, so if you want to use it, you should use your own API, haha, after all, he is his biological son

LocalDate newLocalDate = LocalDate.of(2017, 6, 21).minusWeeks(1l)
                                                  .with(DayOfWeek.MONDAY);

Haha, isn’t it very concise? Isn’t it more concise than the illegitimate child of Joda-Time? It’s so cool~~~Quack

我想大声告诉你

LocalDate.now().minusWeeks(1).minusDays(LocalDate.now().getDayOfWeek().getValue()-1)
This is how I write it now, I don’t know if there is a better way

曾经蜡笔没有小新
    public static void getLastMonday(){
        LocalDate local = LocalDate.now();//获取当前时间
        DayOfWeek dayOfWeek = local.getDayOfWeek();//获取今天是周几
        LocalDate lastMonday = local.minusDays(7+dayOfWeek.getValue()-1);//算出上周一
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!