如何用java比较两个时间或日期的大小

有一个字符串的时间,比如"2012-12-31 16:18:36" 与另一个时间做比较,如果前者比后者早,则返回true,否则返回false。

为此,我设计了一个方法。

import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
class Test
{
	public boolean compare(String time1,String time2) throws ParseException
	{
		//如果想比较日期则写成"yyyy-MM-dd"就可以了
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		//将字符串形式的时间转化为Date类型的时间
		Date a=sdf.parse(time1);
		Date b=sdf.parse(time2);
		//Date类的一个方法,如果a早于b返回true,否则返回false
		if(a.before(b))
			return true;
		else
			return false;
		/*
		 * 如果你不喜欢用上面这个太流氓的方法,也可以根据将Date转换成毫秒
		if(a.getTime()-b.getTime()<0)
			return true;
		else
			return false;
		*/
	}
	public static void main(String[] args) throws Exception
	{
		boolean result=new Test().compare("2012-11-30 16:11:16", "2012-11-30 16:18:18");
		System.out.println(result);
	}
}

结果输出true

很简单实用,希望大家喜欢~

原文地址:https://www.cnblogs.com/james1207/p/3295156.html