Java 在特定日期后下周一获得第一个?

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

Get first next Monday after certain date?

javadatecalendar

提问by Ridzuan Adris

I know there is the same question here, but I have tried the answer provided and it returned an output that I don't understand. I am confused by the answer and I don't think the output is correct.

我知道有同样的问题在这里,但我已经试过了答案提供和它返回的输出,我不明白。我对答案感到困惑,我认为输出不正确。

I need help, thank you :)

我需要帮助,谢谢:)

GregorianCalendar date1 = new GregorianCalendar( 2014, 05, 12 ); //05 is june as month start from 0 -11

while( date1.get( Calendar.DAY_OF_WEEK ) != Calendar.MONDAY )
    date1.add( Calendar.DATE, 1 );  

System.out.println(date1);

Here is the output:

这是输出:

java.util.GregorianCalendar[time=1405267200000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Singapore",offset=28800000,dstSavings=0,useDaylight=false,transitions=9,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=14,DAY_OF_YEAR=195,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=28800000,DST_OFFSET=0]

Where on the output should I extract to retrieve Monday's date?

我应该在输出的哪个位置提取以检索星期一的日期?

采纳答案by MadProgrammer

Java 8+

Java 8+

LocalDate ld = LocalDate.of(2014, Month.JUNE, 12);
System.out.println(ld);
ld = ld.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println(ld);

Which prints...

哪个打印...

2014-06-12
2014-06-16

Because it's possible that the date my actually be a Monday, you could also use...

因为我的日期可能实际上是星期一,所以您也可以使用...

ld = ld.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));

Java <= 7

爪哇 <= 7

You should be using the ThreeTen Backport, which gives you the support of the Java 8 Date/Time API

您应该使用ThreeTen Backport,它为您提供 Java 8 Date/Time API 的支持

Original Answer

原答案

Instead of System.out.println(date1);use System.out.println(date1.getTime());

而不是System.out.println(date1);使用System.out.println(date1.getTime());

getTimereturns an instance of Datewhich represents the current state of the Calendar

getTime返回一个Date代表当前状态的实例Calendar

Which will output Mon Jul 14 00:00:00 EST 2014

哪个会输出 Mon Jul 14 00:00:00 EST 2014

System.out.println(date1)is the equivlent of using System.out.println(date1.toString()), which, in this case, is dumping a bunch of useful info about the state of the Calendarobject, but not really human readable data.

System.out.println(date1)是 using 的等价物System.out.println(date1.toString()),在这种情况下,它正在转储一堆关于Calendar对象状态的有用信息,但不是真正的人类可读数据。

System.out.println(date1.getTime())will use the Date's to toStringmethod to display a date value, formatted based on the current local settings, which will provide more useful information.

System.out.println(date1.getTime())将使用Date's totoString方法显示基于当前本地设置格式化的日期值,这将提供更多有用的信息。

Updated

更新

Instead of using GregorianCalendar, you should use the system Calendar, for example...

GregorianCalendar您应该使用 system而不是 using ,Calendar例如...

Calendar date1 = Calendar.getInstance();
date1.set(2014, 06, 12);

Also, months are 0indexed, meaning that Janurary is actually 0not 1, so in your example, you've specified the month as July, not June.

此外,月份已0编入索引,这意味着 Janurary 实际上0不是1,因此在您的示例中,您已将月份指定为 7 月,而不是 6 月。

So, instead, using...

因此,相反,使用...

Calendar date1 = Calendar.getInstance();
date1.set(2014, 05, 12);

while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
    date1.add(Calendar.DATE, 1);
}

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

Which outputted...

哪个输出...

Mon Jun 16 16:22:26 EST 2014

Which is next Monday from today...more or less ;)

从今天开始是下周一......或多或少;)

回答by npinti

A minor change to your code:

对您的代码稍作改动:

    GregorianCalendar date1 = new GregorianCalendar(2014, 6, 12);

    while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        date1.add(Calendar.DATE, 1);
    }

    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    System.out.println(sdf.format(date1.getTime()));

Yields:

产量:

 14-07-2014

EDIT: As per the JavaDocdocumentation, the constructor you are using, expects a 0 based month index, so for the month of June, you will need to pass in a value of 5, not 6.

编辑:根据JavaDoc文档,您正在使用的构造函数需要一个基于 0 的月份索引,因此对于 6 月份,您需要传入 5 而不是 6 的值。

回答by javaGirl243

Just a suggestion - Instead of looping, you could just use the switch statement along with the Calendar.add() like this:

只是一个建议 - 而不是循环,你可以像这样使用 switch 语句和 Calendar.add() :

int weekdayNum = c.get(Calendar.DAY_OF_WEEK);

    switch (weekdayNum) {
    case 1: {
        c.add(Calendar.DAY_OF_MONTH, 1);
        break;
    }
    case 3: {
        c.add(Calendar.DAY_OF_MONTH, 6);
        break;
    }
    case 4: {
        c.add(Calendar.DAY_OF_MONTH, 5);
        break;
    }
    case 5: {
        c.add(Calendar.DAY_OF_MONTH, 4);
        break;
    }
    case 6: {
        c.add(Calendar.DAY_OF_MONTH, 3);
        break;
    }
    case 7: {
        c.add(Calendar.DAY_OF_MONTH, 2);
        break;
    }
    default:
        break;
    }

回答by Dalancer

Or Just do some simple math. Since Calender.Mondayequals 2, it is easy to calculate the number of days that need to be added to the current date.

或者只是做一些简单的数学运算。由于Calender.Monday等于 2,因此很容易计算需要添加到当前日期的天数。

Calendar date1 = Calendar.getInstance();
date1.set(2014, 05, 12);
int dayOfWeek = date1.get(Calendar.DAY_OF_WEEK);
date1.add(Calendar.DATE, (9 - dayOfWeek) % 7);

回答by Basil Bourque

tl;dr

tl;博士

LocalDate.of( 2014 , Month.JUNE , 12 )
         .with( TemporalAdjusters.next( DayOfWeek.MONDAY ) )

Using java.time

使用 java.time

You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

您正在使用麻烦的旧日期时间类,这些类现在是遗留的,被 java.time 类取代。

The LocalDateclass represents a date-only value without time-of-day and without time zone.

LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

LocalDate ld = LocalDate.of( 2014 , Month.JUNE , 12 ) ;

To get the following Monday, use a TemporalAdjusterimplementation found in TemporalAdjustersclass.

要获得下一个星期一,请使用TemporalAdjusterTemporalAdjusters课堂上找到的实现。

LocalDate nextMonday = ld.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) ;

If you want to go with the original date if it is itself a Monday, then use nextOrSameadjuster.

如果您想使用原始日期(如果它本身是星期一),则使用nextOrSame调整器。

LocalDate nextOrSameMonday = ld.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) ;


About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多