Check if Date is Today in Java

In Java, you can use the classes java.util.Date and java.util.Calendar to determine if a date is today.

Use the methods of the java.util.Date class to determine if a date is today.

import java.util.Date;

public class Main {
    public static void main(String[] args) {
        // 创建一个当前日期时间的Date对象
        Date currentDate = new Date();
        
        // 创建一个指定日期的Date对象
        Date specifiedDate = new Date(121, 2, 21); // 2021年3月21日
        
        // 判断指定日期是否是今天
        boolean isToday = isSameDay(currentDate, specifiedDate);
        
        // 输出结果
        System.out.println("Is the specified date today? " + isToday);
    }
    
    // 判断两个日期是否是同一天
    public static boolean isSameDay(Date date1, Date date2) {
        // 使用Date的getYear、getMonth和getDate方法获取年、月、日
        int year1 = date1.getYear();
        int month1 = date1.getMonth();
        int day1 = date1.getDate();
        
        int year2 = date2.getYear();
        int month2 = date2.getMonth();
        int day2 = date2.getDate();
        
        // 判断年、月、日是否相等
        return (year1 == year2 && month1 == month2 && day1 == day2);
    }
}

Check if a date is today by using methods from the java.util.Calendar class.

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        // 创建一个当前日期时间的Calendar对象
        Calendar currentCalendar = Calendar.getInstance();
        
        // 创建一个指定日期的Calendar对象
        Calendar specifiedCalendar = Calendar.getInstance();
        specifiedCalendar.set(Calendar.YEAR, 2021);
        specifiedCalendar.set(Calendar.MONTH, 2); // 3月
        specifiedCalendar.set(Calendar.DAY_OF_MONTH, 21);
        
        // 判断指定日期是否是今天
        boolean isToday = isSameDay(currentCalendar, specifiedCalendar);
        
        // 输出结果
        System.out.println("Is the specified date today? " + isToday);
    }
    
    // 判断两个日期是否是同一天
    public static boolean isSameDay(Calendar calendar1, Calendar calendar2) {
        // 使用Calendar的get方法获取年、月、日
        int year1 = calendar1.get(Calendar.YEAR);
        int month1 = calendar1.get(Calendar.MONTH);
        int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
        
        int year2 = calendar2.get(Calendar.YEAR);
        int month2 = calendar2.get(Calendar.MONTH);
        int day2 = calendar2.get(Calendar.DAY_OF_MONTH);
        
        // 判断年、月、日是否相等
        return (year1 == year2 && month1 == month2 && day1 == day2);
    }
}

Both of these methods can be used to determine if the specified date is today.

bannerAds