用Java写一个时间输出
时间: 2024-06-11 17:05:21 浏览: 13
以下是一个简单的Java程序,用于输出当前时间:
```
import java.util.Date;
public class TimeOutput {
public static void main(String[] args) {
Date currentTime = new Date();
System.out.println("当前时间是:" + currentTime);
}
}
```
这个程序使用了Java提供的`Date`类来获取当前时间,并使用`System.out.println()`方法将当前时间输出到控制台。
相关问题
用java写一个时间工具类
好的,以下是一个简单的时间工具类的代码示例:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeUtils {
/**
* 获取当前时间戳
*
* @return 当前时间戳
*/
public static long getCurrentTimestamp() {
return System.currentTimeMillis();
}
/**
* 将时间戳转换为指定格式的日期字符串
*
* @param timestamp 时间戳
* @param format 日期格式
* @return 日期字符串
*/
public static String timestampToDate(long timestamp, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new Date(timestamp));
}
}
```
使用示例:
```java
public static void main(String[] args) {
// 获取当前时间戳
long currentTimestamp = TimeUtils.getCurrentTimestamp();
System.out.println("当前时间戳:" + currentTimestamp);
// 将时间戳转换为指定格式的日期字符串
String dateStr = TimeUtils.timestampToDate(currentTimestamp, "yyyy-MM-dd HH:mm:ss");
System.out.println("当前时间:" + dateStr);
}
```
输出结果:
```
当前时间戳:1627834623153
当前时间:2021-08-01 16:43:43
```
用Java程序写一个时间钟
好的,以下是一个用Java编写的时间钟程序:
```java
import java.util.Calendar;
import java.util.Date;
public class TimeClock {
public static void main(String[] args) {
while (true) {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
System.out.printf("%02d:%02d:%02d\n", hour, minute, second);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这个程序会不断输出当前的时间,每秒钟更新一次。
相关推荐
![](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)