java判断时间差

1、判断当前系统时间和自定义时间相差xx秒

	while(true){
			SimpleDateFormat fmtrq = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
			Date now = new Date();
			String value="2020-11-02 09:18:26";
			Date robottime = fmtrq.parse(value);
			if(now.getTime()-robottime.getTime()>=10000){//1000表示1秒
				System.out.println("超过10秒");
			}else{
				System.out.println("没有超过10秒");
			}
	}

2、判断两个时间相差xx天xx小时xx分钟xx秒

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferentExample {

	public static void main(String[] args) {
		String dateStart = "2022-02-19 09:29:58";
		String dateStop = "2022-02-20 11:31:48";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d1 = null;
		Date d2 = null;
		try {
			d1 = format.parse(dateStart);
			d2 = format.parse(dateStop);
			//毫秒ms
			long diff = d2.getTime() - d1.getTime();
			long diffSeconds = diff/1000 % 60;
			long diffMinutes = diff/(60 * 1000) % 60;
			long diffHours = diff/(60 * 60 * 1000) % 24;
			long diffDays = diff/(24 * 60 * 60 * 1000);
			System.out.print("两个时间相差:");
			System.out.print(diffDays + " 天, ");
			System.out.print(diffHours + " 小时, ");
			System.out.print(diffMinutes + " 分钟, ");
			System.out.print(diffSeconds + " 秒.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值