用java写今日年月日
时间: 2024-03-09 18:22:07 浏览: 14
您可以使用Java中的Date类和SimpleDateFormat类来实现输出今日的年月日。以下是示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String today = dateFormat.format(date);
System.out.println(today);
}
}
```
运行结果将输出格式为"yyyy-MM-dd"的今天的日期,例如"2022-01-01"。希望对您有所帮助!
相关问题
用Java写一个随机年月日
以下是用Java写一个随机年月日的代码:
import java.time.LocalDate;
import java.time.Month;
import java.util.Random;
public class RandomDateGenerator {
public static void main(String[] args) {
Random random = new Random();
int year = random.nextInt(100) + 1920; // 生成1920年到2019年之间的随机年份
int month = random.nextInt(12) + 1; // 生成1月到12月之间的随机月份
int day = 1;
if (month == 2) { // 如果是2月份,需要判断是否是闰年
if (LocalDate.of(year, Month.JANUARY, 1).isLeapYear()) {
day = random.nextInt(29) + 1; // 闰年2月份有29天
} else {
day = random.nextInt(28) + 1; // 平年2月份有28天
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) { // 如果是4月、6月、9月或11月,有30天
day = random.nextInt(30) + 1;
} else { // 其它月份有31天
day = random.nextInt(31) + 1;
}
System.out.println(year + "-" + month + "-" + day);
}
}
这个程序会生成一个随机的年月日,例如:1987-7-23。
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日" 的时间字符串。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)