【问题标题】:What is the best way to compare a String date and Date Object in java?在java中比较字符串日期和日期对象的最佳方法是什么?
【发布时间】:2015-06-23 16:34:47
【问题描述】:

我正在阅读具有字符串 endDate 的人员对象列表。在编写迭代器时,我有条件返回公司的活跃用户。这意味着 endDate 应该在今天之前。所以当我这样做时:

   String date = person.getEndDate();
        Date endDate = null;
        Date today = new Date();
       SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");
       endDate = sdf.parse(date);

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(endDate);
        cal2.setTime(today);

        cal1.clear(Calendar.HOUR);
        cal1.clear(Calendar.MINUTE);
        cal1.clear(Calendar.SECOND);
        cal1.clear(Calendar.MILLISECOND);
        cal1.clear(Calendar.HOUR_OF_DAY);

        cal2.clear(Calendar.HOUR);
        cal2.clear(Calendar.MINUTE);
        cal2.clear(Calendar.SECOND);
        cal2.clear(Calendar.MILLISECOND);
        cal2.clear(Calendar.HOUR_OF_DAY);

                 if (cal1 != null && cal1.before(cal2)) {
                return person;
            }else{
                return null;
            }

这会将 endDate 设置为:Tue Jun 23 00:00:00 EDT 2015 但在撰写本文时,今天的日期变为:Tue Jun 23 12:09:01 EDT 2015

比较 cal1.before(cal2) 时,这不会产生活跃或非活跃用户。在这种情况下比较最有效的方法是什么?有什么建议吗?

【问题讨论】:

  • 在发布此类问题之前,请从 StackOverflow.com(或其他地方)获取数百个工作代码示例之一,并一次一步将其更改为您想要的目的。您的问题与其他问题重复。

标签: java string list date iterator


【解决方案1】:

您的日期格式错误。Refer DateFormat m 是分钟 M 是月份,您还必须格式化当前日期才能进行比较。

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date today = sdf.parse(sdf.format(new Date()));
Date date2 = sdf.parse("06/25/2015");
System.out.println(date2.after(today));

【讨论】:

  • 谢谢!这是有道理的!
【解决方案2】:

您似乎只需要整个 Calendar 对象中的日期。 您是否考虑过使用JodaTime 库?它提供了很多日期时间操作选项,也解决了线程安全问题。

使用JodaTime,您的代码可以重写如下:

以下是您可能需要的导入:

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

代码:

        String date = person.getEndDate();
        DateTime endDate = null;
        DateTime today = new DateTime();
        DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy");
        endDate = dtf.parseDateTime(date);

        LocalDate cal1 = endDate.toLocalDate();
        LocalDate cal2 = today.toLocalDate();

        if (cal1 != null && cal1.isBefore(cal2)) {
            return person;
        } else {
            return null;
        }

希望这有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 2013-02-26
    • 2012-06-02
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    相关资源
    最近更新 更多