如何使用Java比较日期

我的格式为2012-02-02(yyyy-MM-dd)。

例如,如果今天的日期是2012-02-02,我需要添加一天半,这将使它成为2012-02-03 06:00:00.0。

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

在比较日期是否小于,大于或等于或等于其他日期和时间时,比较还应该照顾小时数。

我如何实现同样的目标。

那么我希望这会给你一个清晰的想法。 日历文档和SimpleDateFormat 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. 

简单的算术方法(更快)

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

API方法(较慢)

  1. 使用日历
  2. add(...)方法添加1天半
  3. 使用Calendar的before()after()equals()方法
  • 使用SimpleDateFormatString转换为Date

  • 将日期设置为Calendar实例

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

另见

  • Joda Time API

您需要使用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);