java 获取当前一周的所有天数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10429331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:00:37  来源:igfitidea点击:

Get all days of a current week?

java

提问by sandalone

I need to get numbers of all days of a week (MON to SUN) based on which day is sent as a parameter.

我需要根据作为参数发送的日期来获取一周中所有天数(MON 到 SUN)的数字。

For example,
I pass May 2 and I get an array [30,1,2,3,4,5,6] which is this week actually.
Or, I pass May 16 and I get an array [14,15,16,17,18,19,20].

例如,
我通过了 5 月 2 日,我得到了一个数组 [30,1,2,3,4,5,6],实际上是本周。
或者,我过了 5 月 16 日,然后得到一个数组 [14,15,16,17,18,19,20]。

I tried to use this code, but it return 7 days from today, which I do not want.

我尝试使用此代码,但它从今天起返回 7 天,这是我不想要的。

        //get which week of month
        Calendar now = Calendar.getInstance();
        now.set(mYear, mMonth, Integer.parseInt(extractedDay));
        int weekOfMonth = now.get(Calendar.WEEK_OF_MONTH);

        //get all days of clicked week
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(mYear, mMonth, Integer.parseInt(extractedDay));

        String[] days = new String[7];
        for (int i = 0; i < 7; i++)
        {
            days[i] = format.format(calendar.getTime());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

But this is not what I need. I need to pass today's day (THU) and to get dates of this week of May - Mon, Apr 30 to Sun, May 6.

但这不是我需要的。我需要通过今天 (THU) 并获取 5 月 - 4 月 30 日星期一至 5 月 6 日星期日的日期。

EDIT

编辑

I realized that I have a code which detects which week of a month it is. Is there a way to use this data and to set a date for Monday? For example, I pass May 16 and then I detect that it's 3rd week of May, and the I set the variable firstDayOfWeek(a new variable) to May 14.

我意识到我有一个代码可以检测它是一个月的哪一周。有没有办法使用这些数据并设置星期一的日期?例如,我过了 5 月 16 日,然后我检测到它是 5 月的第 3 周,然后我将变量firstDayOfWeek(一个新变量)设置为 5 月 14 日。

回答by Andrea Parodi

You have first to subtract the weekday of the day you choose, in order to start from the first day of week. Try the following code:

您必须首先减去您选择的那一天的工作日,以便从一周的第一天开始。试试下面的代码:

public static void main(String[] args){
    Calendar now = Calendar.getInstance();

    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

    String[] days = new String[7];
    int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 2; //add 2 if your week start on monday
    now.add(Calendar.DAY_OF_MONTH, delta );
    for (int i = 0; i < 7; i++)
    {
        days[i] = format.format(now.getTime());
        now.add(Calendar.DAY_OF_MONTH, 1);
    }
    System.out.println(Arrays.toString(days));

}

Today, it output:

今天,它输出:

[04/30/2012, 05/01/2012, 05/02/2012, 05/03/2012, 05/04/2012, 05/05/2012, 05/06/2012]

[04/30/2012、05/01/2012、05/02/2012、05/03/2012、05/04/2012、05/05/2012、05/06/2012]

回答by Moritz Petersen

Your question has already been answered, but I'd like to add a bit. Your code is problematic in two ways:

您的问题已经得到解答,但我想补充一点。您的代码有两个方面的问题:

  1. It uses various data types for the initial date (mYearis intand exactDayis String?).
  2. It mixes parsing, formatting and generation of the result.
  1. 它对初始日期使用各种数据类型(mYearintexactDayString?)。
  2. 它混合了结果的解析、格式化和生成。

That makes it hard for you to test the code!

这让你很难测试代码!

Therefore, I propose a different approach:

因此,我提出了一种不同的方法:

public class DaysOfCurrentWeek {
    public static void main(String[] args) {
        Date refDate = new Date();

        Date[] days = getDaysOfWeek(refDate, Calendar.getInstance().getFirstDayOfWeek());

        for (Date day : days) {
            System.out.println(day);
        }
    }

    private static Date[] getDaysOfWeek(Date refDate, int firstDayOfWeek) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(refDate);
        calendar.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
        Date[] daysOfWeek = new Date[7];
        for (int i = 0; i < 7; i++) {
            daysOfWeek[i] = calendar.getTime();
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        return daysOfWeek;
    }
}

The code works like this:

代码是这样工作的:

  1. Create a reference date (in this example just by using new Date()).
  2. Call getDaysOfWeek()to do the "dirty job". By passing firstDayOfWeekyou are free to choose MONDAYor SUNDAYas start of the week. In this example, I just use the default of the calendar.
  3. Return the result - unformatted, and as Date. This way you can let the calling code decide what to do - print it or do some further calculations.
  1. 创建参考日期(在本例中仅使用new Date())。
  2. 打电话getDaysOfWeek()来做“肮脏的工作”。通过通过,firstDayOfWeek您可以自由选择MONDAYSUNDAY作为一周的开始。在这个例子中,我只使用日历的默认值。
  3. 返回结果 - 未格式化,并作为Date. 通过这种方式,您可以让调用代码决定要做什么 - 打印它或做一些进一步的计算。

Now you can simply test the getDaysOfWeek() method without worrying about formatting or how the reference date has been created.

现在您可以简单地测试 getDaysOfWeek() 方法,而无需担心格式或参考日期是如何创建的。

回答by Manuel

You will need to use this line of code somewhere in you current code:

您需要在当前代码的某处使用这行代码:

calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

it should be at least before the for-loop.

它应该至少在 for 循环之前。

回答by user1097489

you need to set the day afteryou set the date

您需要在设置日期设置日期

calendar.set(mYear, mMonth, Integer.parseInt(extractedDay));calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

calendar.set(mYear, mMonth, Integer.parseInt(extractedDay));calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);