用java写一个一直获取当前时间的代码
时间: 2023-04-10 17:00:42 浏览: 51
可以使用以下代码获取当前时间:
```java
import java.util.Date;
public class GetCurrentTime {
public static void main(String[] args) {
while (true) {
Date now = new Date();
System.out.println(now);
try {
Thread.sleep(1000); // 暂停1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这个程序会一直输出当前时间,每秒钟输出一次。
相关问题
写一个获取当前时间的java代码
可以使用Java中的Date类和SimpleDateFormat类来获取当前时间。以下是一个示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class GetCurrentTime {
public static void main(String[] args) {
// 创建Date对象,表示当前时间
Date now = new Date();
// 创建SimpleDateFormat对象,指定日期格式为"yyyy-MM-dd HH:mm:ss"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 调用format方法将Date对象格式化为字符串
String currentTime = sdf.format(now);
System.out.println("当前时间为:" + currentTime);
}
}
```
运行该程序,输出的结果类似于:
```
当前时间为:2021-06-08 15:30:00
```
用Java写一个目前时间的代码
可以使用Java中的Date类和SimpleDateFormat类来获取当前时间并格式化输出,代码如下:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(now);
System.out.println("当前时间为:" + time);
}
}
```
输出结果为:
```
当前时间为:2021-09-29 14:30:00
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)