java怎么比较时间的大小

Python011

java怎么比较时间的大小,第1张

例子:

String beginTime=new String("2017-06-09 10:22:22")

String endTime=new String("2017-05-08 11:22:22") 

直接用Date自带方法before()和after()比较

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

Date sd1=df.parse(beginTime)

Date sd2=df.parse(endTime)

System.out.println(sd1.before(sd2))

System.out.println(sd1.after(sd2))

用String的compareTo()方法:

Integer i=beginTime.compareTo(endTime)

System.out.println(i)

返回正值是代表左侧日期大于参数日期,反之亦然,日期格式必须一致

转成date格式换成秒数比较秒数大小,getTime()方法

Date sd1=df.parse(beginTime)

Date sd2=df.parse(endTime)

long long1 =sd1.getTime()

long long2= sd2.getTime()

扩展资料:

Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。Java语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程 。

Java具有简单性、面向对象、分布式、健壮性、安全性、平台独立与可移植性、多线程、动态性等特点。Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。

参考资料:java文档date类

首先

按照一定的格式输入两个日期的字符串

然后用simpledateformat类转换成date实例date1,

date2

然后

calendar

cal1

=

calendar.getinstance()

calendar

cal2

=

calendar.getinstance()

cal1.settime(date1)

cal2.settime(date2)

这样你就有了两个表示所输入日期的calendar实例了

calendar可以做很多事

比如用cal1.after(cal2)或者cal1.before(cal2)或者cal1.equals(cal2)或者cal1.compareto(cal2)来比较两个日期时间先后

比如cal.get(calendar.year)可以得到表示该日期年份的整数

同理cal.get(calendar.month)可以得到月份

甚至可以用cal.gettimeinmillis()得到表示该日期的毫秒数

有了这些方法,简单的计算之后就可以得到需要的相差的信息

如果楼主是来求现成的源代码的-

-

我没有

有两个包里有日期的类型,不知道楼主想用哪个?java.util.Date和java.sql.Timestamp两都可以,后面是面对数据库的,before(),after(),equals()就可以比较两个时间之间的关系了!

××××××××××××××××××××××××××××××××××××××××××××

SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

java.util.Date nows=new java.util.Date()

java.util.Date date=dateFormat.parse("2005-09-12 12:36:29")

long hous=(nows.getTime()-date.getTime())/(60*60*1000)

转换成long在比较 可以得到日期相差的时间

×××××××××××××××××××××××××××××××××××××××××××××

date1, date2

long l1=date1.getTime()

long l2=date2.getTime()

if(l1>l2)

{

//说明date1比较新

}

else if(l1 == l2)

{

//说明date1和date2一样

}

else

{

//说明date2比较新

}

×××××××××××××××××××××××××××××××××××××××××

SimpleDateFormat dateFormat=new SimpleDateFormat(sPatten)

String sText = dateFormat.format(dateValue)

得到sText后你爱怎么比就怎么比呀

sPatten =“yyyy” 取年

sPatten =“MM” 取月

sPatten =“dd” 取日

sPatten =“HH” 取小时

sPatten =“mm” 取分

sPatten =“ss” 取秒

××××××××××××××××××××××××××××××××××××××××××

Date date1 = .....

Date date2 = .....

Calendar cal = Calendar.getInstance()

cal.setTime(date1)

int n1 = Calendar.get(Calendar.DATE)

cal.setTime(date2)

int n2= Calendar.get(Calendar.DATE)

if (n1 == n2) {

}

......