【问题标题】:How to compare dates using Java [duplicate]如何使用Java比较日期[重复]
【发布时间】:2012-02-03 03:48:05
【问题描述】:

我有一个格式为 2012-02-02(yyyy-MM-dd) 的日期。

例如,如果今天的日期是 2012 年 2 月 2 日,我需要增加一天半的时间,这将使其成为 2012 年 2 月 3 日 06:00:00.0。

如果我有多个以下格式的日期 2012-02-03 06:30:00.0(yyyy-MM-dd HH:MM:SS.SSS) ,我需要比较所有这些日期是否都更少大于、大于或等于上面加上一天半的日期。

在比较日期是否小于、大于或等于或等于另一个日期和时间时,比较还应注意小时数。

我如何做到这一点。

【问题讨论】:

标签: java datetime


【解决方案1】:

简单的算术方法(更快)

  1. 使用创建Date 对象的SimpleDateFormat 解析日期
  2. 使用Date.getTime()返回long中的UTC值
  3. 将 1 天半转换为毫秒(1.5 天 = 129600000 毫秒)并将其添加到上一步
  4. 如果您想使用 Date 对象本身,请使用 ><==after()before()equals()

API 方法(较慢)

  1. 使用Calendar
  2. add(...)加1天半的方法
  3. 使用日历的before()after()equals()方法

【讨论】:

  • 简单的算术方法会忽略时区(嗯,使用 UTC)。所以“加1.5天”在夏令时面前可能会导致意想不到的结果。您可能想在回答中提及这一点。
【解决方案2】:

所以我希望这会给你一个清晰的想法。 Calendar DocumentationSimpleDateFormat Documentaion

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String aDateString = "2012-02-02";
Date date = sdf.parse(aDateString);
System.out.println("reference date:"+date);

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 36);
System.out.println("added one and half days to reference date: "+cal.getTime());

String newDateString = "2012-02-03 06:30:00.0";
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date newDate = sdf.parse(newDateString);
System.out.println("new date to compare with reference date : "+newDate);

Calendar newCal = Calendar.getInstance();
newCal.setTime(newDate);

if(cal.after(newCal)){
    System.out.println("date is greater than reference that.");
}else if(cal.before(newCal)){
    System.out.println("date is lesser than reference that.");
}else{
    System.out.println("date is equal to reference that.");
}

输出:

reference date:Thu Feb 02 00:00:00 IST 2012
added one and half days to reference date: Fri Feb 03 12:00:00 IST 2012
new date to compare with reference date : Fri Feb 03 06:30:00 IST 2012
date is greater than reference that.

【讨论】:

    【解决方案3】:
    • 使用SimpleDateFormatString转换为Date

    • 将日期设置为Calendar实例

    • 使用calendar.add(Calendar.HOUR, 36)

    另见

    • Joda 时间 API

    【讨论】:

      【解决方案4】:

      您需要使用 Joda 日期时间API

       String strDate="2012-02-02";
       DateTime dateTime=DateTime.parse(strDate);
      
       DateTime newDateTime=dateTime.plusHours(18); 
       System.out.println(dateTime);
       System.out.println(newDateTime);
      

      【讨论】:

      • Joda 是一个很好用的库,但你并不需要
      • Java 内置日历被严重破坏。是的,你知道。
      • 我觉得我应该指出,在 Java 8 之后,你应该使用 java.time.* 的东西,因为它比 Calendar 和 util date 要好得多。
      猜你喜欢
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 2015-01-01
      相关资源
      最近更新 更多