java输出不同格式年月日
时间: 2023-06-29 12:13:25 浏览: 44
可以使用Java中的SimpleDateFormat类来输出不同格式的年月日。以下是一些常用的格式:
1. 输出年月日,例如:2021-09-30
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
System.out.println(date);
```
2. 输出带中文的年月日,例如:2021年09月30日
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String date = sdf.format(new Date());
System.out.println(date);
```
3. 输出带星期的年月日,例如:2021年09月30日 星期四
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E");
String date = sdf.format(new Date());
System.out.println(date);
```
4. 输出只有月日,例如:09月30日
```
SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
String date = sdf.format(new Date());
System.out.println(date);
```
相关问题
java 输出 时间 年月日
您可以使用Java中的SimpleDateFormat类来输出时间中的年月日。以下是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 创建SimpleDateFormat对象,定义输出格式为年月日
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
// 创建Date对象,获取当前时间
Date date = new Date();
// 使用SimpleDateFormat对象将时间格式化为字符串
String formatDate = sdf.format(date);
// 输出时间字符串
System.out.println(formatDate);
}
}
```
执行以上代码,将会输出类似于 "2021年07月29日" 的时间字符串。
java 格式化日期 年月日
在Java中,可以使用SimpleDateFormat类来格式化日期。以下是一个示例代码,演示如何格式化日期为年月日的格式:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static main(String[] args) // 创建一个SimpleDateFormat对象,指定日期格式
SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// 获取当前日期
Date currentDate = new Date();
使用SimpleDateFormat对象将日期格式化为指定格式的字符串
String formattedDate = sdf.format(currentDate);
// 输出格式化后的日期字符串
System.out.println("Formatted Date: " + formattedDate);
}
}
```
在上面的示例中,我们创建了一个SimpleDateFormat对象,并通过构造函数传入日期格式"yyyy-MM-dd",表示年月日的格式。然后,我们使用format()方法将当前日期格式化为指定格式的字符串。最后,我们将格式化后的日期字符串输出到控制台。
你也可以根据需要自定义日期格式,例如"MM/dd/yyyy"表示月日年的格式,"dd/MM/yyyy"表示日月年的格式等。只需将对应的日期格式传递给SimpleDateFormat的构造函数即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)