java - 获取输入日期的最后日期

时间:2018-03-05 15:47:50

标签: java

我正在寻找一种方法来查找从现在起输入日期的最后日期?例如:如果今天是星期一,即2018年5月5日,结果应如下所示:

Input      Output
Monday     05.03.2018
Tuesday    27.02.2018
Wednesday  28.02.2018
Thursday   01.03.2018
Friday     02.03.2018
Saturday   03.03.2018
Sunday     04.03.2018

我希望你能得到这个想法。我无法找到类似的帖子,所以任何帮助都会非常感激

正如评论中所述,这是我的代码:

private String getLastDateOfDayOfWeek(String day, String returnDateFormat) throws ParseException {
        int dayOfWeek = parseDayOfWeek(day, Locale.ENGLISH);

        Calendar cal = Calendar.getInstance(); // Today, now
        if (cal.get(Calendar.DAY_OF_WEEK) != dayOfWeek) {
            // ...
        }
        return new SimpleDateFormat(returnDateFormat).format(cal.getTime());
}

private static int parseDayOfWeek(String day, Locale locale)
            throws ParseException {
        SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", locale);
        Date date = dayFormat.parse(day);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        return dayOfWeek;
}

Atm我有两个函数:一个可以将字符串转换为Calender dayOfWeek编号,另一个函数是我正在搜索的方法。目前它只处理今天的一周正确,一周中每隔一天应该完成工作的部分丢失(评论为......)

1 个答案:

答案 0 :(得分:2)

TL;博士

LocalDate.now().with(                                // Get today’s date, then move to another date.
    TemporalAdjusters.previousOrSame(                // An implementation of `TemporalAdjuster` interface, used for algorithms to move to another date. 
        DayOfWeek.valueOf( “Monday”.toUpperCase() )  // Get the enum Object with te corresponding hard-coded name in English such as `DayOfWeek.MONDAY`. 
    )
)

DayOfWeek

DayOfWeek枚举包含七个对象,每周一个。

这七个对象的名称均为英文,全部为大写。所以你可以从英文单词中获取Object。

String input = “Monday”.toUpperCase() ;
DayOfWeek dow = DayOfWeek.valueOf( input ) ;

其他语言

对于英语以外的语言,请定义一个填充了每个星期几名称的List。使用从DayOfWeek::getDisplayName生成的名称,这是一种自动本地化的方法。按照ISO 8601标准,在星期一开始列表。搜索该列表以查找与您的输入匹配。获取匹配的序号,1-7(不是索引号0-6)。将该数字传递给DayOfWeek.valueOf以获取DayOfWeek个对象。在某些语言中,您需要搜索一对此类列表,因为可以调用替代拼写,以便在没有日期上下文的情况下“独立”使用星期几。

以下是此类的示例。要注意:我只是在没有经过深思熟虑和没有任何严肃测试的情况下掀起了这门课程。使用风险由您自己承担。用法:DayOfWeekDelocalizer.of( Locale.CANADA_FRENCH ).parse( "lundi" )DayOfWeek.MONDAY

package com.basilbourque.example;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.time.DayOfWeek;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

// For a given name of day-of-week in some language, determine the matching `java.time.DayOfWeek` enum object.
// This class is the opposite of `DayOfWeek.getDisplayName` which generates a localized string for a given `DayOfWeek` object.
// Usage… DayOfWeekDelocalizer.of( Locale.CANADA_FRENCH ).parse( "lundi" ) → DayOfWeek.MONDAY
// Assumes `FormatStyle.FULL`, for day-of-week names without abbreviation.
// USE AT YOUR OWN RISK. Rough draft, quickly written. No serious testing.
public class DayOfWeekDelocalizer
{
    @NotNull
    private Locale locale;

    @NotNull
    private List < String > dayOfWeekNames, dayOfWeekNamesStandalone; // Some languages use an alternate spelling for a “standalone” day-of-week used without the context of a date.

    // Constructor. Private, for static factory method.
    private DayOfWeekDelocalizer ( @NotNull Locale locale )
    {
        this.locale = locale;

        // Populate the pair of arrays, each having the translated day-of-week names.
        int daysInWeek = 7; // Seven days in the week.
        this.dayOfWeekNames = new ArrayList <>( daysInWeek );
        this.dayOfWeekNamesStandalone = new ArrayList <>( daysInWeek );

        for ( int i = 1 ; i <= daysInWeek ; i++ )
        {
            this.dayOfWeekNames.add( DayOfWeek.of( i ).getDisplayName( TextStyle.FULL , this.locale ) );
            this.dayOfWeekNamesStandalone.add( DayOfWeek.of( i ).getDisplayName( TextStyle.FULL_STANDALONE , this.locale ) );
        }
//        System.out.println( this.dayOfWeekNames );
//        System.out.println( this.dayOfWeekNamesStandalone );
    }

    // Constructor. Private, for static factory method.
    // Personally, I think it unwise to default implicitly to a `Locale`. But I included this in case you disagree with me, and to follow the lead of the *java.time* classes. --Basil Bourque
    private DayOfWeekDelocalizer ( )
    {
        this( Locale.getDefault() );
    }

    // static factory method, instead of  constructors.
    // See article by Dr. Joshua Bloch. http://www.informit.com/articles/article.aspx?p=1216151
    // The `Locale` argument determines the human language and cultural norms used in de-localizing input strings.
    synchronized static public DayOfWeekDelocalizer of ( @NotNull Locale localeArg )
    {
        DayOfWeekDelocalizer x = new DayOfWeekDelocalizer( localeArg ); // This class could be optimized by caching this object.
        return x;
    }

    // Attempt to translate the name of a day-of-week to look-up a matching `DayOfWeek` enum object. 
    // Returns NULL if the passed String value is not found to be a valid name of day-of-week for the human language and cultural norms of the `Locale` specified when constructing this parent object, `DayOfWeekDelocalizer`.
    @Nullable
    public DayOfWeek parse ( @NotNull String input )
    {
        int index = this.dayOfWeekNames.indexOf( input );
        if ( - 1 == index )
        { // If no hit in the contextual names, try the standalone names.
            index = this.dayOfWeekNamesStandalone.indexOf( input );
        }
        int ordinal = ( index + 1 );
        DayOfWeek dow = ( ordinal > 0 ) ? DayOfWeek.of( ordinal ) : null;  // If we have a hit, determine the DayOfWeek. Else return null.
        return dow;
    }

    // `Object` overrides.

    @Override
    public boolean equals ( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;

        DayOfWeekDelocalizer that = ( DayOfWeekDelocalizer ) o;

        return locale.equals( that.locale );
    }

    @Override
    public int hashCode ( )
    {
        return locale.hashCode();
    }

    public static void main ( String[] args )
    {
        // Quick testing.
        // DayOfWeekDelocalizer x = DayOfWeekDelocalizer.of( Locale.JAPAN );
        if ( DayOfWeekDelocalizer.of( Locale.CANADA_FRENCH ).parse( "lundi" ).equals( DayOfWeek.MONDAY ) )
        {
            System.out.println( "GOOD - Canada French 'lundi' is parsing to DayOfWeek.MONDAY." );
        } else
        {
            System.out.println( "BAD - Canada French 'lundi' is NOT parsing to DayOfWeek.MONDAY." );
        }
    }
}

提示:使用String表示DayOfWeek是笨拙的。您的代码应该传递DayOfWeek枚举对象。

LocalDate

接下来我们需要当前日期。

LocalDate today = LocalDate.now() ;

最好显式声明您所需/预期的时区,而不是隐式依赖JVM的当前默认时区。

ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
LocalDate today = LocalDate.now( z ) ;

TemporalAdjuster

通过应用TemporalAdjuster移至另一个日期。 TemporalAdjusters类提供了我们需要的实现。

TemporalAdjuster ta = TemporalAdjusters.previousOrSame( dow ) ;
LocalDate ld = today.with( ta ) ;

请注意, java.time 使用不可变对象。因此,方法不是修改对象,而是根据原始值生成具有更改值的新的不同对象。

关于 java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和&amp; SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore