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

How to check if it#39;s Saturday/Sunday?(如何查看是否是周六/周日?)
本文介绍了如何查看是否是周六/周日?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这段代码的作用是打印本周从星期一到星期五的日期.它工作得很好,但我想问点别的:如果今天是周六或周日,我希望它在下周显示.我该怎么做?

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?

这是我目前的工作代码(感谢 StackOverflow!):

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...

推荐答案

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 替换为

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.

这篇关于如何查看是否是周六/周日?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Month is not printed from a date - Java DateFormat(月份不是从日期打印的 - Java DateFormat)
java get week of year for given a date(java获取给定日期的一年中的一周)
Get the number of days, weeks, and months, since Epoch in Java(获取自 Java 中的 Epoch 以来的天数、周数和月数)
Is there a good way to get the date of the coming Wednesday?(有什么好方法可以得到即将到来的星期三的日期吗?)
Calendar view for Android GingerBread and before (APIlt;11)(Android GingerBread 及之前的日历视图 (API11))
How to save and retrieve Date in SharedPreferences(如何在 SharedPreferences 中保存和检索日期)