简体   繁体   English

Joda 时间 - 两个日期之间的所有星期一

[英]Joda time - all mondays between two dates

I am using Joda time api in a Spring 3.0 project for the very first time.我第一次在 Spring 3.0 项目中使用 Joda time api。 Now I have a start and end date and I want to get the date for all mondays between these two dates.现在我有一个开始和结束日期,我想获得这两个日期之间所有星期一的日期。 How can I do this ?我怎样才能做到这一点 ?

I have no idea where to start, can someone please advise.我不知道从哪里开始,有人可以建议。 I looked at theis post Joda Time: How to get dates of weekdays on some date interval?我看了乔达时间的帖子:如何在某个日期间隔内获取工作日的日期? and it offered some sort of guidance but its still somewhat vague due to little experience with joda.它提供了某种指导,但由于对 joda 的经验很少,它仍然有些模糊。

LocalDate startDate = new LocalDate(2011, 11, 8);
LocalDate endDate = new LocalDate(2012, 5, 1);

LocalDate thisMonday = startDate.withDayOfWeek(DateTimeConstants.MONDAY);

if (startDate.isAfter(thisMonday)) {
    startDate = thisMonday.plusWeeks(1); // start on next monday
} else {
    startDate = thisMonday; // start on this monday
}

while (startDate.isBefore(endDate)) {
    System.out.println(startDate);
    startDate = startDate.plusWeeks(1);
}

I recently developed Lamma which is designed to solve this exact use case:我最近开发了Lamma ,旨在解决这个确切的用例:

Dates.from(2011, 11, 8).to(2011, 12, 30).byWeek().on(DayOfWeek.MONDAY).build();

and you will get a List<Date> of:你会得到一个List<Date>

Date(2011,11,14)
Date(2011,11,21)
Date(2011,11,28)
Date(2011,12,5)
Date(2011,12,12)
Date(2011,12,19)
Date(2011,12,26)

FYI, the Joda-Time project is now in maintenance mode , with the team advising migration to the java.time classes.仅供参考, Joda-Time项目现在处于维护模式,团队建议迁移到java.time类。

Using java.time使用 java.time

The LocalDate class is java.time is akin to the Joda-Time LocalDate . LocalDate类是 java.time 类似于 Joda-Time LocalDate A date-only value, without time-of-day and without time zone.一个仅限日期的值,没有时间和时区。 One difference is that java.time eschews constructors for factory methods.一个区别是 java.time 避开了工厂方法的构造函数。

LocalDate start = LocalDate.of( 2011 , 11 , 8 );
LocalDate stop = LocalDate.of( 2012 , 5 , 1 );

Collect the Mondays.收集星期一。

List<LocalDate> mondays = new ArrayList<>();

The TemporalAdjuster interface provides for classes that manipulate date-time values. TemporalAdjuster接口提供了操作日期时间值的类。 The TemporalAdjusters class (note the plural name) provides various implementations. TemporalAdjusters类(注意复数名称)提供了各种实现。 We want the nextOrSame and next adjusters, passing the desired DayOfWeek.MONDAY enum object.我们想要nextOrSamenext调整器,传递所需的DayOfWeek.MONDAY枚举对象。

LocalDate monday = start.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) );
while( monday.isBefore( stop ) ) {
    mondays.add( monday );
    // Set up the next loop.
    monday = monday.plusWeeks( 1 );
}

By the way, usually the wise approach in handling a span of time is Half-Open where the beginning is inclusive while the ending is exclusive .顺便说一句,通常处理时间跨度的明智方法是半开式,其中开头是包容性的,而结尾是排斥性的 So in the code above we are running up to, but not including, the stop date.所以在上面的代码中,我们正在运行,但不包括stop日期。

If the ending is inclusive , use the negation of isAfter eg如果结尾包含在内,则使用isAfter的否定,例如

while( !monday.isAfter( stop ) ) {
    //...
}

Here, monday is not after stop means it is before or up to stop .在这里, monday是不是以后stop手段是以前或高达stop


About java.time关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar ,和SimpleDateFormat

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .规范是JSR 310

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式Joda-Time项目建议迁移到java.time类。

You may exchange java.time objects directly with your database.您可以直接与您的数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later.使用符合JDBC 4.2或更高版本的JDBC 驱动程序 No need for strings, no need for java.sql.* classes.不需要字符串,不需要java.sql.*类。 Hibernate 5 & JPA 2.2 support java.time . Hibernate 5 & JPA 2.2 支持java.time

Where to obtain the java.time classes?从哪里获得 java.time 类?

This code takes to string dates and gives the number of sundays and also all the sunday's dates此代码需要字符串日期并给出星期日的数量以及所有星期日的日期

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class FindAllSundays {


public static int getNumberofSundays(String d1, String d2) throws Exception { // object
                                                                                // in
                                                                                // Date
                                                                                // form

    Date date1 = getDate(d1);
    Date date2 = getDate(d2);

    Calendar c1 = Calendar.getInstance();
    c1.setTime(date1);
    Calendar c2 = Calendar.getInstance();
    c2.setTime(date2);
    int sundays = 0;
    while (c2.after(c1)) {
        // System.out.println(" came here ");
        //checks to see if the day1 ....so on next days are sundays if sunday goes inside to increment the counter
        if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            System.out.println(c1.getTime().toString() + " is a sunday ");
            sundays++;

        }
        c1.add(Calendar.DATE, 1);
    }

    System.out.println("number of sundays between 2 dates is " + sundays);

    return sundays;
}
// converts string to date 
public static Date getDate(String s) {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
        date = format.parse(s);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return date;
}

public static void main(String[] arg) throws Exception {
    System.out.println(" " + getNumberofSundays("2005-10-07", "2006-10-01"));
}

} }

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class Get_time {

    public  ArrayList<LocalDate> getmondays(String s,String e)
    {
        LocalDate start = LocalDate.parse(s);
        LocalDate end = LocalDate.parse(e);
        List<LocalDate> totalDates_Mondays = new ArrayList<>();

        while (!start.isAfter(end)) {
            totalDates_Mondays.add(start);
            start = start.plusWeeks(1);
        }
        return (ArrayList<LocalDate>) totalDates_Mondays;
    }

    public static void main(String ...s1) {

        String mon_start = "1600-08-01";
        String mon_end= "2016-12-29";
        Get_time t=new Get_time();
        System.out.println(t.getmondays(mon_start,mon_end));
    }
}

In Java 8 using Stream ,在 Java 8 中使用 Stream ,

LocalDate startDate = LocalDate.of(2019, 2, 1);
LocalDate endDate = LocalDate.of(2019, 2, 28);
long numOfDays = ChronoUnit.DAYS.between(startDate, endDate);
List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).filter( date -> date.getDayOfWeek()==DayOfWeek.MONDAY ).collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM