【问题标题】:Util to get dates for a year用于获取一年的日期
【发布时间】:2020-08-12 08:04:10
【问题描述】:

我有一个表格,我希望将每一行表示为一个日期以及其他一些列来表示该特定日期的特征。所以,基本上我一年会有 365 行。我需要用 Java 编写一个批处理作业,我将通过一个休息端点触发它。我会将特定年份传递给控制器​​(例如 2020 年)。然后,我想要一种方法,它可以让我获得 2020 年所有 366 天(因为 2020 年是闰年)以及周末(周六/周日)或工作日(周一至周五)的日子。

我稍后会批量插入那 366 天的数据库。

谁能帮我写这个实用方法。

【问题讨论】:

  • 2020 年有 366 天...您考虑过闰年吗?到目前为止,您尝试过什么(在 Java 中)?你能告诉我们吗?
  • 我已经更新了我的问题并将其更改为 366。在更轻松的说明中,我只是将它用作示例,同样适用于我所附的表格。请不要看里面的数据,只是一个假人。是的,我将有 365 天的非闰日和 366 天的闰日。
  • 不,我对那个特定的实用方法一无所知。我可以向您展示控制器和其余的 JDBC 批量上传代码,但不确定这是否有帮助。任何有关任何 API 或任何事情的帮助将不胜感激
  • 您的实用程序方法的签名看起来如何?有点像public List<LocalDate> getDaysOfYear(int year)?
  • 是的,你是...可以提取星期几、月份、对应的日历周等等...java.time值得一看,因为它是现代内置-在 Java 的日期和时间 API 中。

标签: java


【解决方案1】:

要接收给定年份的日期列表,您可以使用java.time 创建如下方法:

public static List<LocalDate> getDaysOfYear(int year) {
    // initialize a list of LocalDate
    List<LocalDate> yearDates = new ArrayList<>();
    /*
     * create a year object from the argument
     * to reliably get the amount of days that year has
     */
    Year thatYear = Year.of(year);
    // then just add a LocalDate per day of that year to the list
    for (int dayOfYear = 1; dayOfYear <= thatYear.length(); dayOfYear++) {
        yearDates.add(LocalDate.ofYearDay(year, dayOfYear));
    }
    // and return the list
    return yearDates;
}

您可以使用结果来提取每天的信息(例如在main 中):

public static void main(String[] args) {
    // receive the LocalDates of a given year
    List<LocalDate> yearDates = getDaysOfYear(2020);
    // define a locale for output (language, formats and so on)
    Locale localeToBeUsed = Locale.US;
    
    // then extract information about each date
    for (LocalDate date : yearDates) {
        // or extract the desired parts, like the day of week
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        // the month
        Month month = date.getMonth();
        // the calendar week based on a locale (the one of your system here)
        WeekFields weekFields = WeekFields.of(localeToBeUsed);
        int calendarWeek = date.get(weekFields.weekOfWeekBasedYear());
        // and print the concatenated information (formatted, depending on the locale)
        System.out.println(date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd",
                                                                    localeToBeUsed))
                + ", " + dayOfWeek.getDisplayName(TextStyle.FULL, localeToBeUsed)
                + ", CW " + calendarWeek
                + ", " + month.getDisplayName(TextStyle.FULL, localeToBeUsed));
    }
}

输出将如下所示(为简洁起见,仅包含几行):

2020-01-01, Wednesday, CW 1, January
...
2020-02-29, Saturday, CW 9, February
...
2020-05-08, Friday, CW 19, May
...
2020-12-31, Thursday, CW 1, December

【讨论】:

    猜你喜欢
    • 2012-10-31
    • 2016-11-14
    • 2019-04-10
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多