首页 > 解决方案 > 通过将输入(日期)作为字符串对日期进行排序

问题描述

我有一个问题,我需要根据date of birth. 我尝试使用的记录对记录进行排序,String.comapreTo但它只是按天排序。不是按年或月。

class Sortbydob {
    void sortString(String[] First_name, String[] Last_name, String[] Dob, int[] Percent) {
        String tempvaule;
        int temphold;
        for (int i = 0; i < 3; i++) {
            for (int j = i + 1; j < 3; j++) {
                if (Dob[i].compareTo(Dob[j]) > 0)
{
//Swapping
}


    public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            Sortbyname obj = new Sortbyname();
            String[] First_name = new String[3];
            String[] Last_name = new String[3];
            String[] Dob = new String[3];
            int[] Percent = new int[3];
            for (int i = 0; i < 3; i++) {
                System.out.println("Enter the First Name : ");
                First_name[i] = in.next();
                System.out.println("Enter the First Name : ");
                Last_name[i] = in.next();
                System.out.println("Enter the Dob in DD/MM/YYYY Format : ");
                Dob[i] = in.next();
                System.out.println("Enter the Percentage : ");
                Percent[i] = in.nextInt();

            }

所以我需要输入First and last name, DOB ,percentage并根据出生日期对其进行排序。挑战是我不能使用任何类型的数组列表或链接数组或哈希映射或表或树等。 任何人都可以帮我用基本逻辑排序吗?

标签: javastringdate

解决方案


您需要将日期从 a 转换String为 aDate

您需要执行以下操作:

Date dobDate = new SimpleDateFormat("dd/mm/yyyy").parse(Dob[i]);

将日期转换为Date对象后,您可以使用内置的比较方法对它们进行排序:after() before() equals()

查看如何在 Java 中比较日期?查看详情


推荐阅读