如何在Java中获取给定周数的第一天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2109145/
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-08-13 03:37:58  来源:igfitidea点击:

How to get first day of a given week number in Java

javacalendardayofweek

提问by framara

Let me explain myself. By knowing the week number and the year of a date:

让我解释一下自己。通过知道日期的周数和年份:

Date curr = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(curr);
int nweek = cal.WEEK_OF_YEAR;
int year = cal.YEAR;

But now I don't know how to get the date of the first day of that week. I've been looking in Calendar, Date, DateFormat but nothing that may be useful...

但现在我不知道如何获得那一周的第一天的日期。我一直在寻找日历、日期、日期格式,但没有任何有用的东西......

Any suggestion? (working in Java)

有什么建议吗?(在 Java 中工作)

采纳答案by BalusC

Those fields does not return the values. Those are constantswhich identifies the fields in the Calendarobject which you can get/set/add. To achieve what you want, you first need to get a Calendar, clear it and set the known values. It will automatically set the date to first day of that week.

这些字段不返回值。这些是标识您可以获取/设置/添加的对象中的字段的常量Calendar。要实现您想要的,您首先需要获取Calendar,清除它并设置已知值。它会自动将日期设置为该周的第一天。

// We know week number and year.
int week = 3;
int year = 2010;

// Get calendar, clear it and set week number and year.
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year);

// Now get the first day of week.
Date date = calendar.getTime();

Please learn to readthe javadocsto learn how to use classes/methods/fields and do not try to poke random in your IDE ;)

请学会阅读的javadoc学习如何使用类/方法/字段,不要试图捅在IDE中随机;)

That said, the java.util.Dateand java.util.Calendarare epic failures. If you can, consider switching to Joda Time.

也就是说,java.util.Datejava.util.Calendar史诗般的失败。如果可以,请考虑切换到Joda Time

回答by Morfildur

I haven't done much Date stuff in java but a solution might be:

我在 Java 中没有做过太多 Date 的事情,但一个解决方案可能是:

cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_WEEK));

Logic:

逻辑:

Get the day of the week and substract it from the current date (might need -1, depending on wether you need monday to be first day of the week or sunday)

获取星期几并将其从当前日期中减去(可能需要 -1,具体取决于您需要星期一作为一周的第一天还是星期日)

回答by SOA Nerd

Here's some quick and dirty code to do this. This code creates a calendar object with the date of the current day, calculates the current day of the week, and subtracts the day of the week so you're on the first one (Sunday). Although I'm using DAY_OF_YEAR it goes across years fine (on 1/2/10 it'll return 12/27/09 which is right).

这是一些快速而肮脏的代码来做到这一点。此代码创建一个带有当天日期的日历对象,计算一周中的当前日期,然后减去一周中的某一天,因此您处于第一个(星期日)。尽管我使用的是 DAY_OF_YEAR,但它可以持续数年(在 1/2/10 它将返回 12/27/09,这是正确的)。

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class DOW {

    public static void main(String[] args) {
        DOW dow = new DOW();
        dow.doIt();
        System.exit(0);
    }

    private void doIt() {
        Date curr = new Date(); 
        Calendar cal = Calendar.getInstance(); 
        cal.setTime(curr); 
        int currentDOW = cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.DAY_OF_YEAR, (currentDOW * -1)+1);

        Format formatter = new SimpleDateFormat("MM/dd/yy");
        System.out.println("First day of week="+formatter.format(cal.getTime()));
    }
}

回答by MarianP

Be cautious with those, calendar.get(Calendar.WEEK_OF_YEAR)returns 1 if it is end of December and already a week that ends in the next year.

小心这些,calendar.get(Calendar.WEEK_OF_YEAR)如果是 12 月底并且已经是明年结束的一周,则返回 1。

Using

使用

//            cal2.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR));
//            cal2.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

sets the cal2 date to e.g. end of 2009 on 29/12/2010 !!

将 cal2 日期设置为例如 2009 年底 29/12/2010 !!

I used this:

我用过这个:

cal2.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)); //to round at the start of day
cal2.set(Calendar.YEAR, cal.get(Calendar.YEAR));
cal2.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); //to round at the start of week

I also make sure that weeks in my calendars, no matter what locale they are in, are starting on Mondays:

我还确保我的日历中的几周,无论他们在什么语言环境中,都从星期一开始:

cal.setFirstDayOfWeek(Calendar.MONDAY);
cal2.setFirstDayOfWeek(Calendar.MONDAY);

回答by Vojta

Try this:

尝试这个:

public static Calendar setWeekStart(Calendar calendar) {
  while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
    calendar.add(Calendar.DATE, -1);
  }
  setDayStart(calendar); // method which sets H:M:S:ms to 0
  return calendar;
}

回答by chim

Yet another way...

还有一种方式...

    GregorianCalendar cal = new GregorianCalendar();
    cal.clearTime();
    Integer correction = 1-cal.get(GregorianCalendar.DAY_OF_WEEK)
    cal.add(Calendar.DATE, correction);

cal is now the first day of the week

cal 现在是一周的第一天

1-cal.get(GregorianCalendar.DAY_OF_WEEK)

1-cal.get(GregorianCalendar.DAY_OF_WEEK)

evaluates to 1-1 for Sunday (first day of week in my Locale) and 1-2 for Monday, so this will give you the correction needed to rewind the clock back to Sunday

周日(在我的语言环境中的第一天)评估为 1-1,周一为 1-2,因此这将为您提供将时钟倒回周日所需的更正

回答by NovoBook

Try the Gregorian Calendar algorithm:

试试公历算法:

public int getFirstDay(int m, int year)
    {
        int k=1;
        int c, y, w, M=0;
        if(m>2 && m<=12) M=m-2;
        else if(m>0 && M<=2)
        {
            M=m+10;
            year-=1;
        }
        c=year/100;
        y=year%100;
        w=(int)((k+(Math.floor(2.6*M - 0.2))-2*c+y+(Math.floor(y/4))+(Math.floor(c/4)))%7);//a fantastic formula           
        if(w<0) w+=7;
        return w;//thus the day of the week is obtained!
    }