Java 如何获取一周的日期(我知道周数)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3941700/
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
How to get dates of a week (I know week number)?
提问by Mellon
I know the week number of the year, a week is start from Sunday, then Monday, Tuesday...,Saturday.
我知道一年中的周数,一周是从星期日开始,然后是星期一,星期二......,星期六。
Since I know the week number, what's the efficient way to get the dates of the specific week by using Java code??
既然我知道周数,那么使用 Java 代码获取特定周日期的有效方法是什么?
采纳答案by bungrudi
If you don't want external library, just use calendar.
如果您不想要外部库,只需使用日历。
SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 23);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(sdf.format(cal.getTime()));
回答by Alois Cochard
回答by mezzie
You did not mention what return type do you exactly need but this code should prove useful to you. sysouts and formatter are just to show you the result.
您没有提到您究竟需要什么返回类型,但这段代码应该对您有用。sysouts 和 formatter 只是为了向您展示结果。
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.WEEK_OF_YEAR, 30);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(formatter.format(cal.getTime()));
cal.add(Calendar.DAY_OF_WEEK, 6);
System.out.println(formatter.format(cal.getTime()));
回答by Mateusz Szulc
回答by Ashish
This answer is pretty much same as others. But, here it goes:
这个答案与其他答案几乎相同。但是,这里是:
int year = 2018;
int week = 27;
int day = 1; //assuming week starts from sunday
Calendar calendar = Calendar.getInstance();
calendar.setWeekDate(year, week, day);
System.out.println(calendar.getTime());