java判断当前时间是否与设定时间是否相同?其中设定时间有键盘输入
时间: 2023-07-29 09:05:53 浏览: 55
你可以使用Java中的Scanner类来读取键盘输入的设定时间,然后使用Calendar类来比较设定时间和当前时间是否相同,以下是示例代码:
```java
import java.util.Calendar;
import java.util.Scanner;
public class CompareTime {
public static void main(String[] args) {
// 创建一个Scanner对象,用于读取键盘输入
Scanner scanner = new Scanner(System.in);
// 读取键盘输入的设定时间,格式为"yyyy-MM-dd HH:mm:ss"
System.out.print("请输入设定时间(格式为yyyy-MM-dd HH:mm:ss):");
String input = scanner.nextLine();
// 将设定时间解析为Calendar对象
Calendar set = Calendar.getInstance();
set.setTimeInMillis(parseDateTime(input));
// 创建一个Calendar对象,表示当前时间
Calendar now = Calendar.getInstance();
// 将时间格式化为中国常用格式
String nowStr = formatDateTime(now.getTimeInMillis());
String setStr = formatDateTime(set.getTimeInMillis());
System.out.println("当前时间:" + nowStr);
System.out.println("设定时间:" + setStr);
// 比较当前时间和设定时间是否相同
if (now.compareTo(set) == 0) {
System.out.println("当前时间与设定时间相同");
} else {
System.out.println("当前时间与设定时间不同");
}
// 关闭Scanner对象
scanner.close();
}
// 将时间字符串解析为毫秒数
private static long parseDateTime(String dateTime) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.parse(dateTime).getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
// 将毫秒数格式化为中国常用格式的时间字符串
private static String formatDateTime(long dateTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
return sdf.format(new Date(dateTime));
}
}
```
运行以上代码,会提示用户输入设定时间,然后输出当前时间和设定时间的字符串表示,并比较它们是否相同。如果设定时间格式不正确,则会抛出异常。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)