如何使用Java比较日期 [英] How to compare dates using Java

查看:105
本文介绍了如何使用Java比较日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a date with the format 2012-02-02(yyyy-MM-dd).

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

For example if todays date is 2012-02-02 i need to add one and a half days to it which would make it 2012-02-03 06:00:00.0.

如果我有一些日期的以下格式2012-02-03 06:30:00.0(yyyy-MM-dd HH:MM:SS.SSS),我需要比较所有这些日期是否小于,大于或等于

And if i have a number of dates of the following format 2012-02-03 06:30:00.0(yyyy-MM-dd HH:MM:SS.SSS) , i need to compare if all these dates are less than,greater than or equal to the date to which one and a half days were added above.

如果日期小于,大于或等于或等于其他日期,比较还应照顾小时数和/或>时间。

The comparison should also take care of the hours while comparing if the dates are less than,greater than or equal or equal to the other date and time.

如何实现相同的方式。

推荐答案

所以我希望这将给你一个明确的想法。 日历文档 SimpleDateFormat Documentaion

well so i hope this will give you a clear idea. Calendar Documentation and 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.");
}

OUTPUT:

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.

这篇关于如何使用Java比较日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆