java 系统时间格式化输出字符串
时间: 2023-11-18 19:53:48 浏览: 46
可以使用 SimpleDateFormat 类来格式化输出系统时间。具体代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
```
其中,SimpleDateFormat 的参数 "yyyy-MM-dd HH:mm:ss" 表示输出的时间格式为年-月-日 时:分:秒。
相关问题
java给定日期字符串,将它格式化输出
Java 中可以使用 SimpleDateFormat 类来将日期字符串按照指定的格式进行格式化输出。以下是一个示例代码,将给定的日期字符串 "2022-06-01 14:30:00" 格式化为 "yyyy年MM月dd日 HH:mm:ss" 的字符串:
```
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
String dateString = "2022-06-01 14:30:00";
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
try {
Date date = originalFormat.parse(dateString);
String formattedDate = targetFormat.format(date);
System.out.println(formattedDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
输出结果为格式化后的日期字符串 "2022年06月01日 14:30:00"。在代码中,首先定义了一个原始日期格式和目标日期格式的 SimpleDateFormat 对象,然后使用原始日期格式的 parse() 方法将给定的日期字符串解析为 Date 对象,最后使用目标日期格式的 format() 方法将 Date 对象格式化为目标格式的字符串。在解析日期字符串时,需要注意捕获 ParseException 异常。
Java字符串之String类格式化字符串之日期时间格式化输出
Java中可以使用String类的format()方法进行字符串格式化,其中可以使用日期时间格式化输出。具体实现方法如下:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class DateFormatExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(date);
System.out.println("Formatted Date: " + formattedDate);
}
}
```
上述代码中,我们首先创建了一个Date对象,然后创建了一个SimpleDateFormat对象,指定了日期时间格式化的格式为"yyyy-MM-dd HH:mm:ss",然后使用format()方法将Date对象格式化为字符串,并输出到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)