当字段为空时如何处理DateTimeParseException

问题描述 投票:0回答:1

如果字段为空,如何根据日期对列表进行排序?

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;

 class Person implements Comparable < Person > {

    private String name;
    private String birthdate;

    public Person(String name, String birthdate) {
        this.name = name;
        this.birthdate = birthdate;
    }



    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getBirthdate() {
        return birthdate;
    }
    public void setBirthdate(String birthdate) {
        this.birthdate = birthdate;
    }




    @Override
    public int compareTo(Person otherPerson) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");

        LocalDate currentPersonDate = LocalDate.parse(birthdate, formatter);      
        LocalDate otherPersonDate = LocalDate.parse(otherPerson.getBirthdate(), formatter); 
        int retVal = otherPersonDate.compareTo(currentPersonDate); // 1 Comparing With Dates DESC
        return retVal;
    }




}

// 2009-06-23 00:00:00.0
public class TestClient {
    public static void main(String args[]) {  
        ArrayList < Person > personList = new ArrayList < Person > ();

        Person p1 = new Person("Shiva ", "2020-09-30 00:00:00.0");
        Person p2 = new Person("pole", "2020-09-30 00:00:00.0");
        Person p3 = new Person("Balal ", "");

        personList.add(p1);
        personList.add(p2);
        personList.add(p3);

        Collections.sort(personList);


        System.out.println("After Descending sort");
        for(Person person: personList){
            System.out.println(person.getName() + " " + person.getBirthdate());
        }


    }
}
java
1个回答
0
投票

您可以使用try-catch捕获异常,并根据异常情况的排序顺序返回-101的某个值

try {

     LocalDate currentPersonDate = LocalDate.parse(birthdate, formatter);      
     LocalDate otherPersonDate = LocalDate.parse(otherPerson.getBirthdate(), formatter); 
    return otherPersonDate.compareTo(currentPersonDate);

   }catch(DateTimeParseException ex) {
      //log error
   }
     return -1;
© www.soinside.com 2019 - 2024. All rights reserved.