JAVA如何对两个日期进行比较呢?

欣喜 Java经验 发布时间:2024-01-30 15:46:59 阅读数:9977 1
下文笔者讲述java代码对两个日期进行比较的方法及示例分享,如下所示
比较两个日期的方法:
    借助data对象的after和before方法
    即可实现比较两个日期
例:比较两个日期的示例
 
 public static SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    public static SimpleDateFormat format1 = new SimpleDateFormat(
            "yyyyMMdd HH:mm:ss");

    /**
     *  比较指定日期
     * @param date
     * @param compareDate
     * @return  compareDate日期在date日期之间  返回true  
     */
    public static boolean isInDate(Date date, Date compareDate) {
        if (compareDate.after(getStartDate(date))
                && compareDate.before(getFinallyDate(date))) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 得到指定日期的一天的的最后时刻23:59:59
     *
     * @param date
     * @return
     */
    public static Date getFinallyDate(Date date) {
        String temp = format.format(date);
        temp += " 23:59:59";

        try {
            return format1.parse(temp);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 得到指定日期的一天的开始时刻00:00:00
     *
     * @param date
     * @return
     */
    public static Date getStartDate(Date date) {
        String temp = format.format(date);
        temp += " 00:00:00";

        try {
            return format1.parse(temp);
        } catch (Exception e) {
            return null;
        }
    }
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202401/17066008507857.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者