java 获取日期 星期与日
时间: 2023-08-10 20:03:40 浏览: 90
可以使用 Java 中的 `java.util.Calendar` 类来获取日期和星期。以下是一个示例代码:
```java
import java.util.Calendar;
public class DateExample {
public static void main(String[] args) {
// 获取当前时间
Calendar cal = Calendar.getInstance();
// 获取日期
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
// 获取星期
int weekday = cal.get(Calendar.DAY_OF_WEEK);
String[] weekdays = {"", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
String weekDayName = weekdays[weekday];
System.out.println("Today is " + weekDayName + ", " + month + "/" + day + "/" + year);
}
}
```
运行结果:
```
Today is Monday, 9/20/2021
```
其中,`Calendar.DAY_OF_WEEK` 表示星期几,取值为 1 到 7,分别表示周日到周六。
阅读全文