java语言编程实现数字时钟,用多种格式输出时间信息
时间: 2024-05-01 19:23:52 浏览: 129
以下是Java语言编程实现数字时钟的示例代码,同时提供了多种格式输出时间信息的方法:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DigitalClock {
public static void main(String[] args) {
while(true) {
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
// 输出时间信息
System.out.println("24小时制:" + formatTime(hour, minute, second, true));
System.out.println("12小时制:" + formatTime(hour, minute, second, false));
System.out.println("hh:mm:ss:" + formatTime(hour, minute, second, "HH:mm:ss"));
System.out.println("hh:mm a:" + formatTime(hour, minute, second, "hh:mm a"));
System.out.println("HH:mm:ss.SSS:" + formatTime(hour, minute, second, "HH:mm:ss.SSS"));
try {
Thread.sleep(1000); // 暂停1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 格式化时间信息
private static String formatTime(int hour, int minute, int second, boolean is24Hour) {
if(is24Hour) {
return String.format("%02d:%02d:%02d", hour, minute, second);
} else {
if(hour > 12) {
hour %= 12;
}
return String.format("%02d:%02d:%02d %s", hour, minute, second, hour < 12 ? "AM" : "PM");
}
}
private static String formatTime(int hour, int minute, int second, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
return sdf.format(cal.getTime());
}
}
```
运行上述代码,会实现一个数字时钟,每秒钟更新一次时间信息,并且输出多种格式的时间信息,例如:
```
24小时制:13:01:45
12小时制:01:01:45 PM
hh:mm:ss:13:01:45
hh:mm a:01:01 PM
HH:mm:ss.SSS:13:01:45.968
```
你可以根据需要选择输出哪种格式的时间信息。
阅读全文