猿问

用工作日处理 Java 日历的最佳方式?

我需要实施一个能够计算工作日和自然天数的劳动日历。日历必须能够处理国定假日,这些日子必须由用户提交。因此,如果我需要计算两天之间的差异,计数必须忽略星期六、星期日和节假日。

Java 类Calendar,不处理假期或工作日,所以我需要自己制作。我想了两种可能的方法:

第一种方式:

我可以实现一个新Day类,它有一个布尔值isHoliday来检查这是否是工作日,然后使用我需要处理/计算天数的所有方法创建一个新类。

优点:

  • 易于处理

  • 我可以覆盖/创建像 toString、toDate 等方法...

缺点:

  • (也许?)

我对这种方法的疑问是如何存储它。这意味着制作 365 个对象并将它们存储在一个Listor 中Linked List,这需要处理大量数据。

第二种方式:

我的第二个想法是让它更简单。创建一个Strings日期数组,我将在其中存储假期。示例new ArrayList<String> freeDays = ["01/01/2019", "05/01/2019", "06/01/2019"...]并使用新的 CalendarUtils 类或类似的东西使用它。

优点:

  • 更具可读性

缺点:

  • 很难合作

对我来说,第一个选项看起来更好,但是,我不想浪费内存或使用不好的做法。

哪个选项看起来更好?有没有第三种选择?


慕的地10843
浏览 145回答 1
1回答

慕丝7291255

避免遗留的日期时间类永远不要使用Date或Calendar类。那些非常麻烦的旧类现在是遗留的,被java.time类所取代,特别是Instant和ZonedDateTime.&nbsp;你也可能会觉得LocalDate有帮助。智能对象,而不是哑字符串切勿在 Java 代码中使用字符串来表示日期时间。使用对象,java.time类。将日期时间值作为文本交换时,请始终使用标准 ISO 8601 格式。该java.time类解析/生成字符串时,在默认情况下使用这些格式。对于 YYYY-MM-DD 的日期,例如2018-01-23.TemporalAdjuster&nbsp;界面要跳过周末,使用TemporalAdjuster中发现的实施ThreeTen-EXTRA项目。nextWorkingDaypreviousWorkingDay例子:LocalDate&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Represent a date-only value, without a time-of-day and without a time zone.&nbsp;.now(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Capture the current date.&nbsp;&nbsp; &nbsp; ZoneId.of( "Africa/Tunis" )&nbsp; // Time zone required. For any given moment the date varies around the globe by zone.&nbsp;).with(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Invoke a `TemporalAdjuster` implementation.&nbsp;&nbsp; &nbsp; org.threeten.extra.Temporals.nextWorkingDay()&nbsp;)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Returns a `LocalDate`. Using immutable objects pattern, producing a fresh object based on the values of another while leaving the original unaltered.&nbsp;要跳过假期,您必须编写自己的代码。没有两个人、公司或国家对假期有相同的定义。您需要定义自己的假期列表。我建议将其编写为TemporalAdjuster与java.time类一起工作的实现。也许nextBusinessDay和previousBusinessDay。这ThreeTen-EXTRA项目上面提到的是开源的,所以看看那里的代码来指导你。我依稀记得TemporalAdjuster在 Stack Overflow 上发布了我自己的一个或多个实现。您可以将这些假期日期存储在数据库中以保持持久性。并在运行时按时间顺序将它们表示为 a&nbsp;List< LocalDate >,用 排序Collections.sort和搜索Collections.binarySearch。但要注意线程安全。您可能需要在运行时更新该列表。阅读时写作必须受到保护。搜索更多信息。并阅读Brian Goetz 等人的优秀著作Java Concurrency in Practice。您可以将假期跳过代码与周末跳过代码结合使用。使用搜索引擎在周末跳过使用EnumSet和DayOfWeek枚举找到我的答案。(不幸的是,Stack Overflow 中内置的搜索功能偏向于问题,而忽略了答案。)搜索堆栈溢出。所有这些都已经被问过和回答过。
随时随地看视频慕课网APP

相关分类

Java
我要回答