java 获取当前时间string
时间: 2023-07-06 22:34:49 浏览: 41
你可以使用 Java 中的 SimpleDateFormat 类来获取当前时间的字符串表示。以下是一个示例代码:
```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 strDate = formatter.format(date);
System.out.println(strDate);
}
}
```
这个代码将会输出当前时间的字符串表示,格式为 "yyyy-MM-dd HH:mm:ss",例如 "2022-01-01 12:00:00"。你可以根据需要修改格式化字符串来获得不同的时间格式。
相关问题
java获取当前时间String型
以下是两种Java获取当前时间String型的例子:
1. 使用java.time包获取当前时间:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TimeString {
public static void main(String[] args) {
String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("当前时间:" + currentTime);
}
}
```
2. 使用java.util包获取当前时间:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class TimeString {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = format.format(now);
System.out.println("当前时间:" + currentTime);
}
}
```
java获取系统时间String
以下是Java获取系统时间的代码示例:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class GetSystemTime {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
System.out.println("当前系统时间为:" + time);
}
}
```
运行结果:
```
当前系统时间为:2022-08-17 16:30:00
```
该代码使用了Java自带的Date类和SimpleDateFormat类,通过SimpleDateFormat类的format方法将Date对象格式化为指定格式的字符串,从而获取当前系统时间的字符串表示。
相关推荐
![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)
![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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)