Java judges that the current date and time is greater than the specified date and time to record small searches in daily development

You can use Calendarthe class to get the current time and the desired specified time and compare them. Here is a sample code:

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        Calendar now = Calendar.getInstance(); // 获取当前时间
        Calendar target = Calendar.getInstance(); // 获取指定时间

        // 设置指定时间为2022年1月1日下午3点30分0秒
        target.set(Calendar.YEAR, 2022);
        target.set(Calendar.MONTH, Calendar.JANUARY);
        target.set(Calendar.DAY_OF_MONTH, 1);
        target.set(Calendar.HOUR_OF_DAY, 15);
        target.set(Calendar.MINUTE, 30);
        target.set(Calendar.SECOND, 0);

        // 比较当前时间和指定时间
        if (now.after(target)) {
            System.out.println("当前时间晚于指定时间");
        } else {
            System.out.println("当前时间早于指定时间");
        }
    }
}

In the above example, we first use Calendar.getInstance()the method to get the current time and Calendarthe object of the specified time. We then set the specified time to 3:30 PM on January 1, 2022, and use after()the method to compare the current time with the specified time. It will output if the current time is later than the specified time 当前时间晚于指定时间. Otherwise, it will output 当前时间早于指定时间.

You can use LocalDateTimethe class to get the current datetime and the specified datetime and compare them. Here is a sample code:

import java.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now(); // 获取当前日期时间
        LocalDateTime target = LocalDateTime.of(2022, 1, 1, 15, 30, 0); // 指定日期时间为2022年1月1日下午3点30分0秒

        // 比较当前日期时间和指定日期时间
        if (now.isAfter(target)) {
            System.out.println("当前日期时间晚于指定日期时间");
        } else {
            System.out.println("当前日期时间早于指定日期时间");
        }
    }
}

In the above example, we first use LocalDateTime.now()the method to get the current datetime, and then use LocalDateTime.of()the method to specify a datetime. We set the specified datetime to January 1, 2022 at 3:30:00 PM. Then, we use isAfter()the method to compare the current datetime with the specified datetime. It will output if the current datetime is later than the specified datetime 当前日期时间晚于指定日期时间. Otherwise, it will output 当前日期时间早于指定日期时间.

Guess you like

Origin blog.csdn.net/zl18603543572/article/details/130438813