避免 j.u.Date
第一个错误是使用 Java 捆绑的 java.util.Date 和 .Calendar 类。他们是出了名的麻烦。避开他们。
使用合适的日期时间库。在 Java 中,这意味着:
- Joda-Time
- Java 8 中的 java.time 包(受 Joda-Time 启发)
两者各有利弊。
两者都提供LocalDate 类,您需要用它来表示一个没有任何时间部分的纯日期。
日期时间与文本
问题的代码将日期时间值与其字符串表示形式混合在一起。最好使用日期时间值完成您的工作。之后,分别创建字符串表示以呈现给用户。这个想法是separation of concerns,让你的代码更清晰,更容易测试/调试。
乔达时间
Java-Time 中的示例代码。
您必须指定一周中的哪几天是工作日。
注意时区的使用。当前日期取决于您在地球上的位置(时区)。巴黎的新一天比蒙特利尔更早。如果省略时区,则应用 JVM 的默认值。最好指定,即使通过调用 getDefault(),也比依赖隐式默认值。
首先,我们收集所需日期时间值的集合。
int requiredCountOfDays = 10; // The Question demands 10 previous working days.
List<LocalDate> days = new ArrayList<LocalDate>( requiredCountOfDays ); // Collect desired LocalDate objects.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); // Specify time zone by which to get current date.
LocalDate today = LocalDate.now( timeZone ); // Get the current date at this moment in specified time zone.
LocalDate localDate = today; // Define var to decrement for previous days.
while ( days.size() < requiredCountOfDays ) { // Loop until we fill the list (10 elements).
localDate = localDate.minusDays( 1 ); // Decrement to get previous day.
// Hard-code what days are business days vs weekend days.
boolean isWeekend = ( ( localDate.getDayOfWeek() == DateTimeConstants.SATURDAY ) || ( localDate.getDayOfWeek() == DateTimeConstants.SUNDAY ) ); // Hard-coding for weekend because it is easier to type than coding for the more numerous week days.
if ( !isWeekend ) { // If business day…
days.add( localDate ); // …collect this day.
}
}
之后,我们以本地化的字符串格式呈现这些值。
List<String> daysOfWeek = new ArrayList<String>( days.size() ); // Collect the same number of LocalDate objects, rendered as Strings.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE" ); // Generate name of day-of-week, abbreviated.
for ( LocalDate day : days ) {
String dayOfWeek = formatter.print( day ); // Generate String representation.
daysOfWeek.add( dayOfWeek ); // Collect the string.
}
转储到控制台...
System.out.println( "days: " + days );
System.out.println( "daysOfWeek: " + daysOfWeek );
运行时……
days: [2014-06-18, 2014-06-17, 2014-06-16, 2014-06-13, 2014-06-12, 2014-06-11, 2014-06-10, 2014-06-09, 2014-06-06, 2014-06-05]
daysOfWeek: [Wed, Tue, Mon, Fri, Thu, Wed, Tue, Mon, Fri, Thu]