此代码的作用是打印当周从星期一到星期五的日期。它工作正常,但我想问别的:如果今天是星期六或星期日,我希望它显示下周。我该怎么做?
到目前为止,这是我的工作代码(感谢StackOverflow !!):
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday to Friday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i <= 4; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
非常感谢!我真的很感激,因为我一直在寻找解决方案......
答案 0 :(得分:25)
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday to Friday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i <= 10; i++) {
System.out.println(df.format(c.getTime()));
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.FRIDAY) { // If it's Friday so skip to Monday
c.add(Calendar.DATE, 3);
} else if (dayOfWeek == Calendar.SATURDAY) { // If it's Saturday skip to Monday
c.add(Calendar.DATE, 2);
} else {
c.add(Calendar.DATE, 1);
}
// As Cute as a ZuZu pet.
//c.add(Calendar.DATE, dayOfWeek > Calendar.THURSDAY ? (9 - dayOfWeek) : 1);
}
}
<强>输出强>
Mon 03/01/2011
Tue 04/01/2011
Wed 05/01/2011
Thu 06/01/2011
Fri 07/01/2011
Mon 10/01/2011
Tue 11/01/2011
Wed 12/01/2011
Thu 13/01/2011
Fri 14/01/2011
Mon 17/01/2011
如果你想变得可爱,可以用
替换if / then / elsec.add(Calendar.DATE, dayOfWeek > 5 ? (9 - dayOfWeek) : 1);
但我真的想要一些容易理解和可读的东西。
答案 1 :(得分:16)
核心代码概念:
EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) // Instantiate a n implementation of `Set` highly optimized in both memory usage and execution speed for collecting enum objects.
.contains( // Ask if our target `DayOfWeek` enum object is in our `Set`.
LocalDate.now( ZoneId.of( "America/Montreal" ) ) // Determine today’s date as seen by the people of a particular region (time zone).
.getDayOfWeek() // Determine the `DayOfWeek` enum constant representing the day-of-week of this date.
)
现代的方法是使用java.time类。
DayOfWeek
枚举为星期一到星期日提供七个对象。
LocalDate
类表示没有时间且没有时区的仅限日期的值。
时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DayOfWeek dow = today.getDayOfWeek();
将周末定义为一组DayOfWeek
个对象。请注意,EnumSet
是Set
的一种特别快速且内存不足的实现,旨在保存Enum
等DayOfWeek
个对象。
Set<DayOfWeek> weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY );
现在我们可以测试今天是工作日还是周末。
Boolean todayIsWeekend = weekend.contains( dow );
问题说如果这是一个周末,我们想跳到下周的开始。为此,请使用TemporalAdjuster
,它提供可以操作日期时间对象的类。在java.time中,我们有immutable objects。这意味着我们根据现有对象中的值生成新实例,而不是改变(&#34; mutate&#34;)原始实例。 TemporalAdjusters
课程(请注意复数&#39;)提供了TemporalAdjuster
的几个便捷实施,包括next( DayOfWeek )
。
DayOfWeek firstDayOfWeek = DayOfWeek.MONDAY ;
LocalDate startOfWeek = null ;
if( todayIsWeekend ) {
startOfWeek = today.with( TemporalAdjusters.next( firstDayOfWeek ) );
} else {
startOfWeek = today.with( TemporalAdjusters.previousOrSame( firstDayOfWeek ) );
}
如果周末的定义发生变化,我们会对本周的长度进行软编码。
LocalDate ld = startOfWeek ;
int countDaysToPrint = ( DayOfWeek.values().length - weekend.size() );
for( int i = 1 ; i <= countDaysToPrint ; i++ ) {
System.out.println( ld );
// Set up the next loop.
ld = ld.plusDays( 1 );
}
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和&amp; SimpleDateFormat
现在位于Joda-Time的maintenance mode项目建议迁移到java.time。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如Interval
,YearWeek
,YearQuarter
和more。
答案 2 :(得分:0)
这是使用 Java 8 的简短回答,您需要做的就是将您的 Calendar 实例转换为 LocalDateTime 并利用 DayOfWeek 枚举来检查它是星期六还是星期日,给您...
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i <= 20; i++) {
//following line does all magic for you
if(LocalDateTime.ofInstant(c.toInstant(), ZoneId.systemDefault()).getDayOfWeek()!=DayOfWeek.SATURDAY && LocalDateTime.ofInstant(c.toInstant(), ZoneId.systemDefault()).getDayOfWeek()!=DayOfWeek.SUNDAY)
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}