比较两个字符串作为日期,并检索月份和年份

时间:2019-04-23 13:22:23

标签: java

如果日期匹配,我想打印出结果,具体取决于月份或特定日期。

目前,如果日期完全匹配,我只能得到它以打印出正确的消息;第一个日期是通过用户输入生成的,因此,如果发生更改,我想将其与第二个日期进行比较,以查看年和月是否仍然相同。如果它们相同,我也想打印“正确”。

String date1 = "2018-02-04";
String date2 = "2018-02-04";

if(date1.trim().equals(date2.trim())){
System.out.println("Correct");
}




ADDED/UPDATED FOR CLARIFICATION:

while (m.hasNextLine()) 
        {   
                carReg = m.next();
                carModel = m.next();
                carType = m.next();
                vehicleSize = m.next();
                carColour = m.next();
                carMileage = m.next();
                carAccidentHistory = m.next();
                carTransmissionType = x.next();
                carCost = m.next();
                DateArrived = m.next();
                DateSold = m.next();


                m.nextLine();



    if(userDate.trim().equals(DateSold.trim())){            

    System.out.println("Correct output.");
                }


// This if condition works fine, but I'm attempting to match the date the user inputs to any date that is being scanned, provided the year and month match. 


3 个答案:

答案 0 :(得分:3)

为什么不只使用LocalDate类呢?

public static void main(String[] args) {
        String date1 = "2018-02-04";
        String date2 = "2018-02-05";

        LocalDate localDate1 = LocalDate.parse(date1);
        LocalDate localDate2 = LocalDate.parse(date2);

        boolean isSameYear = localDate1.getYear() == localDate2.getYear();
        boolean isSameMonth = localDate1.getMonthValue() == localDate2.getMonthValue();

        if(isSameYear && isSameMonth) {
            System.out.println("correct");
        }

    }

编辑:

由于@assylias,我们可以将以前的代码简化为:

public static void main(String[] args) {
        String date1 = "2018-02-04";
        String date2 = "2018-02-05";

        LocalDate localDate1 = LocalDate.parse(date1);
        LocalDate localDate2 = LocalDate.parse(date2);

        if(YearMonth.from(localDate1).equals(YearMonth.from(localDate2))) {
            System.out.println("correct");
        }
    }

答案 1 :(得分:1)

您可以使用Java8执行以下操作。因此,将您的字符串解析为LocalDate实例,并尝试针对所有三种有关日期比较的方案调用日期比较isEqual,isAfter和isBefore的方法。

private Spinner spinner_simple;
spinner_simple = findViewById(R.id.spinner_simple);

final ArrayAdapter<String> adapter_simple = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, 0){

    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        }
        return view;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        }
        return view;
    }

};

adapter_simple.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_simple.setAdapter(adapter_simple);

spinner_simple.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // Note: When an item has been clicked, don't refresh the spinner.
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) { 
    }

});

更新2: 根据您的新请求,如果给定日期的年和月相同,则写出“更正”,您可以执行以下操作:

String date1 = "2018-05-04";
String date2 = "2018-02-04";
//DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);

LocalDate localDate1 = LocalDate.parse(date1);

LocalDate localDate2 = LocalDate.parse(date2);//with formatter  LocalDate.parse(date2,formatter);

//System.out.println(localDate1.isEqual(localDate2) ? "Dates are equal." : localDate1.isAfter(localDate2) ? " Date1 is after Date2 " : " Date1 is before Date2 ");
if (localDate1.isAfter(localDate2)) {
    System.out.println("Date1 is after Date2");
}

else if (localDate1.isBefore(localDate2)) {
    System.out.println("Date1 is before Date2");
}

else {
    System.out.println("Date1 is equal Date2");
}

这将检查从提供的日期到第0年的月数是否相同,如果正确,则返回true,否则返回false,因此只需按照以下步骤进行检查即可

boolean isSameYearAndMonth = localDate1.getLong(ChronoField.PROLEPTIC_MONTH) == localDate2.getLong(ChronoField.PROLEPTIC_MONTH);

UPDATE 3 在这种情况下,最简单的方法是在while循环中添加一个标志,该标志表示年份和月份中的两个日期是否匹配,所以类似的方法可以满足您的需求:

if(isSameYearAndMonth)
{
   System.out.println("Correct");
}
else
{
   System.out.println("Not correct");
}

并在while循环中使用以下方法

 //flag used for entering while loop
        boolean flag = true;
        //two simple variables for simple example
        String variable1, variable2;
        Scanner scanner = new Scanner(System.in);
        while (flag) {
            System.out.println("Enter variable1");
            variable1 = scanner.next();
            System.out.println("Enter date variable:");
            variable2 = scanner.next();

            boolean take = sameMonthSameYear(variable1, variable2);
            if(take)
            {
                //if we finally match two dates, exit while loop
                flag = false;
            }

        }

答案 2 :(得分:0)

您应该使用LocalDate作为其他人已经评论/回答的地方。

但是,如果您要坚持使用字符串并假设输入格式始终相同,则可以使用String.substring(int beginIndex, int endIndex)方法:

String date1 = "2018-02-04";
String date2 = "2018-02-07";

if(date1.substring(0, date1.lastIndexOf('-')).equals(date2.substring(0, date2.lastIndexOf('-')))){
    System.out.println("Correct");
}