java中得到日期并转换成字符
时间: 2023-12-06 19:39:38 浏览: 38
可以使用 Java 中的 SimpleDateFormat 类来将日期格式化成字符串。以下是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToStringExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = dateFormat.format(date);
System.out.println(dateString);
}
}
```
在这个示例中,我们首先创建了一个 Date 对象,表示当前日期和时间。然后,我们创建了一个 SimpleDateFormat 对象,它将日期格式化成 "yyyy-MM-dd HH:mm:ss" 的字符串。最后,我们使用 dateFormat.format(date) 方法将日期对象转换成字符串。
你可以根据需要修改日期格式的字符串。例如,如果你只需要日期部分,可以使用 "yyyy-MM-dd";如果你需要更详细的时间,可以使用 "yyyy-MM-dd HH:mm:ss.SSS"。
相关问题
java中8位日期数字转换成字符串
可以使用Java中的SimpleDateFormat类将8位日期数字转换为字符串。示例代码如下:
```java
int dateInt = 20220101;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String dateString = dateFormat.format(dateInt);
System.out.println(dateString); // 输出结果为:20220101
```
在上面的示例代码中,我们将8位日期数字20220101转换为了字符串"20220101"。其中,SimpleDateFormat中的格式字符串"yyyyMMdd"表示年份、月份和日期的顺序,且均为两位数。具体的格式字符串可以根据实际需求进行修改。
java日期转换成字符串
使用 SimpleDateFormat 类可以将 Java 的 Date 类型转换为字符串。
例如,要将当前日期转换为字符串,可以使用以下代码:
```
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(date);
System.out.println(dateString);
```
输出结果为:
```
2021-09-17 15:30:00
```
其中,SimpleDateFormat 的参数表示要转换的日期格式,例如:
- yyyy:年份,例如 2021。
- MM:月份,例如 09。
- dd:日期,例如 17。
- HH:小时,例如 15。
- mm:分钟,例如 30。
- ss:秒钟,例如 00。
还可以使用其他的日期格式,例如:
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String dateString = sdf.format(date);
System.out.println(dateString);
```
输出结果为:
```
2021/09/17
```
如果要将字符串转换为日期,可以使用 SimpleDateFormat 的 parse() 方法。例如:
```
String dateString = "2021-09-17 15:30:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
System.out.println(date);
```
输出结果为:
```
Fri Sep 17 15:30:00 CST 2021
```
相关推荐
![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)