java 获取两个时间差_JAVA新手,计算两个时间差

展开全部

我的思e5a48de588b63231313335323631343130323136353331333332633639路:在java里面任何完整的日期都可以转化成毫秒,

然后利用毫秒之差就可以算出这2个日期的差额,

但题目里面没有天,只有时分秒,

所以我们可以分别在时分秒加上年月日,使之组成一个完整的日期就可以进行计算了。

以下是我的代码,可以直接拷贝在Eclipse里运行。

p.s:你的代码我看了,没有什么问题,可能是在网站里面运行,你不应该有main函数之类的东西吧,应该用servlet啊。

package com.testtimeinterval;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.text.SimpleDateFormat;

import java.util.Date;

public class TestTimeInterval {

public static void main(String[] args) {

try {

// 得到系统输入的内容

System.out.println("请输入入睡时刻,用:隔开:");

InputStreamReader isr_begin = new InputStreamReader(System.in);

BufferedReader br_begin = new BufferedReader(isr_begin);

String beginInputValue = br_begin.readLine();

System.out.println("入睡时间为:" + beginInputValue);

System.out.println("请输入起床时刻,用:隔开:");

InputStreamReader isr_end = new InputStreamReader(System.in);

BufferedReader br_end = new BufferedReader(isr_end);

String wakeupInputValue = br_end.readLine();

System.out.println("起床时间为:" + wakeupInputValue);

// 1.将入睡时间拼接成一个完整的日期

String sleepTimeStr = getCurrDay() + " " + beginInputValue;

// 1.1转换成日期格式

Date sleepTime = convertStrToDate(sleepTimeStr);

// 2.将起床时间拼接成一个完整的日期

String wakeupTimeStr = getCurrDay() + " " + wakeupInputValue;

// 2.1转换成日期格式

Date wakeupTime = convertStrToDate(wakeupTimeStr);

// 计算2个日期之差

long interval = wakeupTime.getTime() - sleepTime.getTime();

System.out.println("相差的毫秒是:" + interval);

// 3.将long转化成时分秒

// 3.1先得到时

int hour = new Long(interval / (1000 * 60 * 60)).intValue();

// 3.2再得到分

int tempLeft_minute = new Long(interval % (1000 * 60 * 60))

.intValue();

// 3.2.1 得到分

int minute = new Long(tempLeft_minute / (1000 * 60)).intValue();

// 4.1 得到秒

int tempLeft_second = new Long(tempLeft_minute % (1000 * 60))

.intValue();

// 4.2.1 得到分

int second = new Long(tempLeft_second / 1000).intValue();

System.out.println("睡觉的时间为" + hour + "时," + minute + "分," + second

+ "秒");

} catch (Exception e) {

e.printStackTrace();

}

}

private static String getCurrDay() throws Exception {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

return sdf.format(new Date());

}

private static Date convertStrToDate(String dateStr) throws Exception {

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

return sdf.parse(dateStr);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值