【问题标题】:Using Java Dates, Given a year, I want a method that should return a list of dates representing a given day of the week, all 52 times使用 Java 日期,给定一年,我想要一个方法应该返回代表一周中给定日期的日期列表,全部 52 次
【发布时间】:2014-07-02 02:44:56
【问题描述】:

一个方法接收一个表示年份的整数和一个表示星期几的整数。该方法应返回代表一周中给定日期的日期列表。例如,如果年份是 2014 年,星期几是 2,那么该方法应该返回代表 2014 年所有星期一的日期列表。

public List<Date> getDatesforDayOfWeek(int year, int dayOfWeek) throws InvalidDateException

我不太确定最好的代码是什么。有什么建议吗?

if (year <= 0) {
    throw new InvalidDateException("Invalid year.");
}
if ((dayOfWeek < 1) || (dayOfWeek > 7)) {
    throw new InvalidDateException("Invalid day.");
}
DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");

【问题讨论】:

  • “最佳代码”是什么意思?你尝试过什么?
  • Calendar 将是我的第一站,但如果您使用的是 Java 8,您还可以查看新的 Time API,如果您可以使用 3rd 方 API,甚至可以查看 JodaTime

标签: java date


【解决方案1】:

检查这个适用于非闰年(以及经过一些修改的闰年)的实现

public List<Date> getDatesforDayOfWeek(int year, int dayOfWeek)
            throws InvalidDateException {

        if (year <= 0) {
            throw new InvalidDateException("Invalid year.");
        }
        if ((dayOfWeek < 1) || (dayOfWeek > 7)) {
            throw new InvalidDateException("Invalid day.");
        }

        List<Date> dates = new ArrayList<Date>();

        // Start with the given inputs
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        int day = cal.get(Calendar.DAY_OF_WEEK);
        while (day != dayOfWeek) {
            cal.add(Calendar.DATE, 1);
            day = cal.get(Calendar.DAY_OF_WEEK);
        }

        // Make this 366 for a leap year
        for (int i = 0; i < 365; i += 7) {
            if (cal.get(Calendar.DAY_OF_WEEK) == dayOfWeek
                    && cal.get(Calendar.YEAR) == year) {
                dates.add(cal.getTime());
                cal.add(Calendar.DATE, 7);
            }
        }

        return dates;
    }

    public static void main(String[] args) throws InvalidDateException {
        for (Date date : new DateList().getDatesforDayOfWeek(2014, 4)) {
            System.out.println(date);
        }

    }

}

class InvalidDateException extends Exception {

    public InvalidDateException(String string) {
        super(string);
    }

    private static final long serialVersionUID = 1L;

}

【讨论】:

  • 当您知道每个感兴趣的日子之间有固定的间隔时,每天都回顾一下似乎很浪费。我知道它很小,但你的 for 循环应该真的有 += 7。
  • 这正是我所需要的。
  • 后续问题:如何让列表在其自己的行上打印所有内容?
  • 这会将所有内容打印在一行上。
  • 有没有办法让星期一的每个实例都打印在自己的行上? >:D
【解决方案2】:

如果我理解你的问题,我会使用Calendar 来解决这个问题(实际上我会先选择Joda-Time,否则日历因为有很多极端情况需要处理)-

public static List<Date> getDatesforDayOfWeek(int year, int dayOfWeek) {
  List<Date> al = new ArrayList<>();
  if (dayOfWeek >= 1 && dayOfWeek <= 7) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    while (cal.get(Calendar.DAY_OF_WEEK) != dayOfWeek) {
      cal.add(Calendar.DAY_OF_MONTH, 1);
    }
    for (int i = 0; i < 52; i++) {
      al.add(cal.getTime());
      cal.add(Calendar.DAY_OF_MONTH, 7);
    }
  }
  return al;

}

public static void main(String[] args) {
  System.out.println(getDatesforDayOfWeek(2014, 2));
}

输出为(格式化,省略50行,用于显示)

[Mon Jan 06 23:52:16 EST 2014, 
...     
Mon Dec 29 23:52:16 EST 2014]

【讨论】:

  • 这只会给出一个月中一天的第一次出现。 OP 需要一年中的所有事件(52 或 53)。
  • @NikhilTalreja 好收获!谢谢!已编辑。
【解决方案3】:

查看所有答案,他们将为您提供所需的内容。这是我认为比以前的答案更有效的另一种方法。

public static List<Date> GetDatesForDayOfWeek(int year, int dayOfWeek)
{

        // Days in the week
        final int DAYS_IN_WEEK = 7;

        List<Date> dates = new ArrayList<Date>();

        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, 0);                   // January
        c.set(Calendar.DAY_OF_MONTH, 1);            // The first

        // Find the first day we are interested in
        int offset = c.get(Calendar.DAY_OF_WEEK);
        if(offset!= dayOfWeek)
        {
            c.add(Calendar.DATE, (dayOfWeek < offset ? (offset + 7) % 7 : (dayOfWeek - offset)));
        }


        while(c.get(Calendar.YEAR) == year)
        {
            dates.add(c.getTime());
            c.add(Calendar.DATE, DAYS_IN_WEEK);
        }

        return dates;

    }



public static void main(String[] args){

    System.out.println("A list of all Sundays in 2014.");
    List<Date> days = GetDatesForDayOfWeek(2014, Calendar.SUNDAY);
    for(Date ad : days){
        System.out.println(ad);
    }
}

运行上述代码将为您提供 2014 年的每个星期日的输出。

    A list of all Sundays in 2014.
    Sun Jan 05 23:49:56 EST 2014
   ...
    Sun Dec 28 23:49:56 EST 2014

【讨论】:

    【解决方案4】:

    新的 Java8 DateTime API 为任何与日期、时间相关的代码提供了非常简洁的方法。 以下是我对您的查询的部分。

    public class ExampleDayOfYear {
    public static void main(String[] args) throws InvalidDateException {
     List<LocalDate> list=getDatesforDayOfWeek(2020,2);
    list.forEach(System.out::println);
        System.out.println("Total dates: "+list.size());
    }
    
    public static String getDay(int day, int month, int year) {
               LocalDate dt=LocalDate.of(year,month,day);
      return dt.getDayOfWeek().toString();
    }
    
    private static int getDayOfYear(int year){
    LocalDate dt = LocalDate.parse(year+"-01-01");
    return dt.getDayOfWeek().getValue();
    }
    
    public static List<LocalDate> getDatesforDayOfWeek(int year, int dayOfWeek) throws 
    InvalidDateException{
        List<LocalDate> list=new ArrayList<LocalDate>();
        int differenceOfdaysToDayofWeek=0;
        int firstDayOfYear= getDayOfYear(year); // Wednesday
    int count=1;
    

    // 这个方法调用给出了第一个星期一的日期。此外,此方法需要我们从 getDaysDifference 中找到的 differenceOfDate。

    LocalDate firstDateOfWeek=getFirstDateOfWeek(year,getDaysDifference(firstDayOfYear));
        list.add(firstDateOfWeek);
        while(firstDateOfWeek.getYear()== year){
            firstDateOfWeek=  getDateWeekWise(firstDateOfWeek);
            if(firstDateOfWeek.getYear()==year){
                     count++;
    
          list.add(firstDateOfWeek);  }
            }
    
     return list;
    }
    

    // 第一天是星期三,所以我们需要得到 2020 年 1 月的第一个日期。

        private static int getDaysDifference(int firstDayOfYear){
        int difDays=0;
        int dayofWeekNum=Integer.valueOf(DayOfWeek.MONDAY.ordinal()+1);
    

    // 它给出 DayOfWeek 的 int 值。例如如果是星期一,它将给出 0,因为周序数值从 0 开始。

        if(firstDayOfYear==dayofWeekNum) {
           }if(firstDayOfYear>dayofWeekNum){
        difDays= dayofWeekNum+7 -firstDayOfYear;
    }if(firstDayOfYear<dayofWeekNum)
    {
        difDays= dayofWeekNum -firstDayOfYear;
    }
    return difDays;
    }
    private static LocalDate getFirstDateOfWeek(int year,int differenceOfWeekDays){
        LocalDate dt = LocalDate.of(year,01,01).plusDays(differenceOfWeekDays);
              return dt;
    }
    
    private static LocalDate getDateWeekWise(LocalDate dt){
        dt=dt.plusWeeks(1);
    return dt;
    }
    }
    class InvalidDateException extends Exception{
    InvalidDateException(String s){
        super(s);
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      相关资源
      最近更新 更多