gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:23:05 27 4
gpt4 key购买 nike

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

目前,如果日期完全匹配,我只能让它打印出正确的消息;第一个日期是根据用户输入生成的,所以如果发生变化,我想将它与第二个日期进行比较,看看年份和月份是否仍然相同。如果它们相同,我也想打印出“正确”。

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.


最佳答案

为什么不直接使用 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");
}
}

关于java - 比较两个字符串作为日期,并检索月份和年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55812243/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com