java 如何获得当前日期之前的最后一个星期日?

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

How to get the last Sunday before current date?

javaandroidcalendar

提问by malcoauri

I have the following code for getting the last Sunday before the current date:

我有以下代码用于获取当前日期之前的最后一个星期日:

Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR)-1);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Log.e("first day", String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));

But this code doesn't work. Please, tell me, how can I fix it?

但是这段代码不起作用。请告诉我,我该如何解决?

回答by Jimmy

This will work. We first get the day count, and then subtract that with the current day and add 1 ( for sunday)

这将起作用。我们首先得到天数,然后用当前天减去它并加1(对于星期天)

Calendar cal=Calendar.getInstance();
cal.add( Calendar.DAY_OF_WEEK, -(cal.get(Calendar.DAY_OF_WEEK)-1)); 
System.out.println(cal.get(Calendar.DATE));

Edit : As pointed out by Basil Bourquein the comment, see the answer by Grzegorz Gajosfor Java 8 and later.

编辑:正如Basil Bourque在评论中所指出的,请参阅Grzegorz Gajos对 Java 8 及更高版本的 回答

回答by Grzegorz Gajos

java.time.temporal.TemporalAdjuster

java.time.temporal.TemporalAdjuster

This can be easily achieved by a TemporalAdjusterimplementation found in TemporalAdjustersalong with the DayOfWeekenum. Specifically, previous?(DayOfWeek dayOfWeek).

这可以通过与枚举一起TemporalAdjuster找到的实现 轻松实现。具体来说,。TemporalAdjustersDayOfWeekprevious?(DayOfWeek dayOfWeek)

 LocalDate
 .now()
 .with(
     TemporalAdjusters.previous( DayOfWeek.SUNDAY )
 ) ;

If today is Sunday and you would like the result to be today rather than a week ago, call previousOrSame?(DayOfWeek dayOfWeek).

如果今天是星期日并且您希望结果是今天而不是一周前,请致电previousOrSame?(DayOfWeek dayOfWeek)

 LocalDate
 .now()
 .with(
     TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY )
 ) ;

These classes are built into Java 8 and later, and built into Android 26 and later. For Java 6 & 7, most of the functionality is back-ported in ThreeTen-Backport. For earlier Android, see ThreeTenABP.

这些类内置于 Java 8 及更高版本中,并内置于 Android 26 及更高版本中。对于 Java 6 和 7,大部分功能在ThreeTen-Backport 中向后移植。对于早期的 Android,请参阅ThreeTenABP

回答by dapek

You could iterate back in steps of one day until you arrive on a Sunday:

您可以以一天为单位进行迭代,直到您在星期日到达:

Calendar cal = Calendar.getInstance();
while (cal.get( Calendar.DAY_OF_WEEK ) != Calendar.SUNDAY)
    cal.add( Calendar.DAY_OF_WEEK, -1 );

or, in only one step, substract the difference in days between sunday and now:

或者,只需一步,减去星期日和现在之间的天数差异:

Calendar cal = Calendar.getInstance();
int dayOfTheWeek = cal.get( Calendar.DAY_OF_WEEK );
cal.add( Calendar.DAY_OF_WEEK, Calendar.SUNDAY - dayOfTheWeek );

回答by Markymark

Here's how to do it with a Kotlin extension and the Joda Time library.
Answer is based on linqu's answer but this also fixes a bug in that answer. The bug was that it did not work if the current date was the same day you're trying to get.

以下是如何使用 Kotlin 扩展和Joda Time 库来实现
答案基于 linqu 的答案,但这也修复了该答案中的错误。错误是如果当前日期与您尝试获取的日期相同,则它不起作用。

/**
 * E.g., DateTimeConstants.SUNDAY
 */
fun DateTime.previousDayOfWeek(day: Int): DateTime {
    var date = this
    if(date.dayOfWeek == day) date = date.minusDays(1)

    val offset = (date.dayOfWeek - day + 7) % 7
    return date.minusDays(offset)
}

fun DateTime.previousSunday(): DateTime {
    return previousDayOfWeek(DateTimeConstants.SUNDAY)
}

回答by cl-r

final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cal.getTimeInMillis() //
     // Saturday is the 7th day of week, so use modulo to get it : remove day between todoay
     - (( cal.get(Calendar.DAY_OF_WEEK) % 7) * 86400000)); // 86400000=24*60*60*1000

System.out.println(cal.getTime());
. . .

回答by Viswanath Lekshmanan

The following works for me irrespective of which month and year.

无论哪个月份和年份,以下内容都适用于我。

 Calendar cal = Calendar.getInstance(TimeZone.getDefault());
 Date date = cal.getTime();
 int days = cal.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
 date.setTime(date.getTime() - (long) (days*1000*60*60*24));
 cal.setTime(date);

回答by linqu

Here is a snippet to calculate any last day of the week with Joda:

这是使用 Joda 计算一周中任何最后一天的片段:

import org.joda.time.DateTime
import org.joda.time.DateTimeConstants

DateTime now = DateTime();
int offset = ((now.dayOfWeek - DateTimeConstants.THURSDAY) + 7) % 7;
DateTime lastThursday = now.minusDays(offset);

Just replace DateTimeConstants.THURSDAYwith your day of choice.

只需替换DateTimeConstants.THURSDAY为您选择的日期。