java获取当前时间,并以字符输出
时间: 2023-07-08 16:51:51 浏览: 55
好的,我可以帮你回答这个问题。在Java中获取当前时间可以使用`java.util.Date`类和`java.text.DateFormat`类。
下面是一个例子:
```java
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class GetCurrentTime {
public static void main(String[] args) {
// 获取当前时间
Date now = new Date();
// 格式化时间
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(now);
// 输出时间
System.out.println(currentTime);
}
}
```
上述代码中,我们首先使用`new Date()`获取当前时间,然后使用`SimpleDateFormat`类将时间格式化为字符串。最后将格式化后的时间字符串输出到控制台。
这样就可以获取当前时间并以字符输出了。
相关问题
java 获取当前时间 然后输出字符串
以下是两种Java获取当前时间并转为字符串的例子:
1. 使用SimpleDateFormat类(Java 7及以下版本)[^1]:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String formattedDate = formatter.format(date);
System.out.println(formattedDate);
}
}
```
2. 使用DateTimeFormatter类(Java 8及以上版本):
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.now();
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime);
}
}
```
java获取当前时间的字符串
您好,可以使用Java中的SimpleDateFormat类来获取当前时间的字符串表示。以下是示例代码:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 创建SimpleDateFormat对象,格式为"yyyy-MM-dd HH:mm:ss"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 创建Date对象,表示当前时间
Date now = new Date();
// 使用SimpleDateFormat对象将Date对象转换为字符串表示
String nowStr = sdf.format(now);
// 输出当前时间的字符串表示
System.out.println("当前时间为:" + nowStr);
}
}
```
输出结果:
```
当前时间为:2022-07-20 14:56:34
```
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)