如何查看是否是周六/周日?

发布于 2024-10-11 01:55:51 字数 599 浏览 0 评论 0原文

此代码的作用是打印本周从星期一到星期五的日期。它工作正常,但我想问其他问题:如果今天是星期六或星期日,我希望它在下周显示。我该怎么做?

这是到目前为止我的工作代码(感谢 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);
}

非常感谢!我真的很感激,因为我已经寻找解决方案几个小时了......

What this code does is print the dates of the current week from Monday to Friday. It works fine, but I want to ask something else: If today is Saturday or Sunday I want it to show the next week. How do I do that?

Here's my working code so far (thanks to 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);
}

Thanks a lot! I really appreciate it as I've been searching for the solution for hours...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

执着的年纪 2024-10-18 01:55:51
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/else 替换,

c.add(Calendar.DATE, dayOfWeek > 5 ? (9 - dayOfWeek) : 1);

但我真的想要一些容易理解和可读的东西。

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);
    }
}

Output

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 you want to be cute you can replace the if/then/else with

c.add(Calendar.DATE, dayOfWeek > 5 ? (9 - dayOfWeek) : 1);

but I really wanted something easily understood and readable.

﹏雨一样淡蓝的深情 2024-10-18 01:55:51

tl;dr

核心代码概念:

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

现代方法是使用 java.time 类。

DayOfWeek 枚举为周一到周日提供了七个对象。

LocalDate类表示仅日期值,没有时间和时区。

时区对于确定日期至关重要。对于任何特定时刻,全球各地的日期都会因地区而异。例如,法国巴黎午夜过后几分钟是新的一天,但仍然是“昨天” ”在魁北克省蒙特利尔

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DayOfWeek dow = today.getDayOfWeek();

将周末定义为一组 DayOfWeek 对象。请注意,EnumSetSet 的一种特别快速且低内存的实现,旨在保存 Enum 对象,例如 DayOfWeek

Set<DayOfWeek> weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY );

现在我们可以测试今天是工作日还是周末。

Boolean todayIsWeekend = weekend.contains( dow );

该问题表示,如果这是周末,我们希望跳至下周初。为此,请使用 TemporalAdjuster,它提供了可以操作日期时间对象的类。在 java.time 中,我们有不可变对象。这意味着我们根据现有对象中的值生成新实例,而不是更改(“变异”)原始实例。 TemporalAdjusters 类(注意复数“s”)提供了 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 );
}

请参阅IdeOne.com 中的实时代码

输入图像描述这里


关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历,& SimpleDateFormat

Joda-Time 项目,现位于 维护模式,建议迁移到 java.time。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 IntervalYearWeekYearQuarter,以及更多

tl;dr

Core code concept:

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

The modern way is with the java.time classes.

The DayOfWeek enum provides seven objects, for Monday-Sunday.

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DayOfWeek dow = today.getDayOfWeek();

Define the weekend as a set of DayOfWeek objects. Note that EnumSet is an especially fast and low-memory implementation of Set designed to hold Enum objects such as DayOfWeek.

Set<DayOfWeek> weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY );

Now we can test if today is a weekday or a weekend.

Boolean todayIsWeekend = weekend.contains( dow );

The Question said we want to jump to the start of next week if this is a weekend. To do that, use a TemporalAdjuster which provides for classes that can manipulate date-time objects. In java.time we have immutable objects. This means we produce new instances based on the values within an existing object rather than alter ("mutate") the original. The TemporalAdjusters class (note the plural 's') provides several handy implementations of TemporalAdjuster including next( DayOfWeek ).

DayOfWeek firstDayOfWeek = DayOfWeek.MONDAY ;
LocalDate startOfWeek = null ;
if( todayIsWeekend ) {
    startOfWeek = today.with( TemporalAdjusters.next( firstDayOfWeek ) );
} else {
    startOfWeek = today.with( TemporalAdjusters.previousOrSame( firstDayOfWeek ) );
}

We soft-code the length of the week in case our definition of weekend ever changes.

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 );
}

See live code in IdeOne.com.

enter image description here


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

笛声青案梦长安 2024-10-18 01:55:51

这是使用 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);
        }

Here is short answer using Java 8, all you need to do is to convert your Calendar instance to LocalDateTime and leverage DayOfWeek enum to check if it's Saturday or Sunday, here you go...

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);
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文