假设数据库存放的日期为字符串类型,可以使用以下代码实现日期判断:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    /**
     * 判断当前日期是否订阅
     * @param subscribeDate 订阅日期,格式为'yyyy-MM-dd'
     * @return true表示订阅,false表示未订阅
     */
    public static boolean isSubscribe(String subscribeDate) {
        try {
            // 将订阅日期转换为Date类型
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format.parse(subscribeDate);

            // 获取当前日期
            Calendar today = Calendar.getInstance();
            int year = today.get(Calendar.YEAR);
            int month = today.get(Calendar.MONTH) + 1; // 月份从0开始,需要加1
            int day = today.get(Calendar.DAY_OF_MONTH);

            // 判断订阅日期与当前日期的年月日是否相同
            if (date.getYear() == year - 1900 && date.getMonth() == month - 1 && date.getDate() == day) {
                return true;
            }

            // 判断订阅日期是否在本月最后一天之前
            int lastDay = getLastDayOfMonth(year, month);
            if (lastDay < date.getDate()) {
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 获取指定年月的最后一天
     * @param year 年份
     * @param month 月份
     * @return 最后一天的日期
     */
    private static int getLastDayOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1); // 将日期设置为指定年月的第一天
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 获取该月最后一天的日期
    }
}

使用示例:

String subscribeDate = '2022-09-30';
boolean isSubscribe = DateUtils.isSubscribe(subscribeDate);
System.out.println(isSubscribe); // 输出true或false
Java 日期判断:检查订阅日期是否已到

原文地址: https://www.cveoy.top/t/topic/ncxT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录