比较两个string类型的日期 并输出时间差

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/buyaopingbixiazai/article/details/84064453
	public static void main(String[] args) throws ParseException {

		String StringTime1 = "2018-08-13 12:20:30";
		String StringTime2 = "2018-08-13 12:20:31";
		String differenceFormat = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//yyyy-mm-dd, 会出现时间不对, 因为小写的mm是代表: 秒
		Date dateTime1 = sdf.parse(StringTime1);
		Date dateTime2 = sdf.parse(StringTime2);
		long difference = dateTime1.getTime() - dateTime2.getTime();
		System.out.println("相差毫秒数:"+difference);
		long days = difference / (1000 * 60 * 60 * 24);
		long hours = (difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
		long minutes = (difference % (1000 * 60 * 60)) / (1000 * 60);
		long seconds = (difference % (1000 * 60)) / 1000;
		differenceFormat = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ";
		System.out.println("相差时间:"+differenceFormat);
	
	}

结果:

相差毫秒数:-1000
相差时间:0 days 0 hours 0 minutes -1 seconds 

猜你喜欢

转载自blog.csdn.net/buyaopingbixiazai/article/details/84064453
今日推荐