1、定义一个方法,入参跟出参都是String,输入“2020年11月13日 14:21:21”,控制台打印与当前时间相差的小时数,返回“2020-11-13 14时21分00秒”,当输入格式错误时,返回“error”。(20分)java实现
时间: 2024-11-30 20:15:27 浏览: 68
在Java中,我们可以定义一个方法`calculateTimeDifference`,首先检查输入字符串的格式是否正确,然后计算与当前时间的时间差并按照指定格式返回结果。以下是一个简单的实现:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
try {
String input = "2020年11月13日 14:21:21";
System.out.println(calculateTimeDifference(input));
} catch (IllegalArgumentException e) {
System.out.println("error");
}
}
public static String calculateTimeDifference(String input) {
SimpleDateFormat formatIn = new SimpleDateFormat("yyyy年M月d日 H:mm:ss");
SimpleDateFormat formatOut = new SimpleDateFormat("yyyyMMdd HH时mm分ss秒");
// 检查输入格式
if (!formatIn.parse(input)) {
throw new IllegalArgumentException("Input format error");
}
Date inputDate = formatIn.parse(input);
Date currentDate = new Date();
long differenceInMilliseconds = Math.abs(currentDate.getTime() - inputDate.getTime());
long hoursDiff = TimeUnit.MILLISECONDS.toHours(differenceInMilliseconds);
// 格式化时间和返回结果
String formattedResult = String.format("%04d-%02d-%02d %02d时%02分00秒",
currentDate.getYear() + 1900,
currentDate.getMonth() + 1,
currentDate.getDate(),
(int) hoursDiff);
return formattedResult;
}
}
```
阅读全文
相关推荐



















