java 取当前日期和时间
时间: 2023-07-04 16:26:49 浏览: 57
可以使用 Java 中的 `java.util.Date` 和 `java.text.SimpleDateFormat` 类来获取当前日期和时间。下面是一个示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class DateTimeExample {
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);
}
}
```
输出结果类似于:`当前日期和时间:2021-08-19 15:30:00`。
相关问题
java 取当前日期和时间跟 date类型时间段做对比 看是否在范围内
可以使用 Java 中的 `java.util.Date` 和 `java.text.SimpleDateFormat` 类来获取当前日期和时间,并使用 `Date` 类的 `before` 和 `after` 方法来判断一个日期是否在另一个日期范围内。下面是一个示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class DateTimeExample {
public static void main(String[] args) {
// 获取当前日期和时间
Date currentDate = new Date();
// 设置日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 定义一个时间段
String startDateStr = "2021-08-18 00:00:00";
String endDateStr = "2021-08-20 00:00:00";
// 将时间段转换为 Date 类型
Date startDate = sdf.parse(startDateStr);
Date endDate = sdf.parse(endDateStr);
// 判断当前日期是否在时间段内
if (currentDate.after(startDate) && currentDate.before(endDate)) {
System.out.println("当前日期在时间段内。");
} else {
System.out.println("当前日期不在时间段内。");
}
}
}
```
在代码中,我们将时间段的开始时间和结束时间先转换为 `Date` 类型,然后使用 `after` 和 `before` 方法来判断当前日期是否在时间段内。如果在时间段内,输出“当前日期在时间段内。”,否则输出“当前日期不在时间段内。”。
LocalDateTime 取当前日期
LocalDateTime 是 Java 8 中的一个日期时间类,它表示了一个不带时区信息的日期时间对象。要取得当前日期,可以使用 LocalDateTime 的静态方法 now(),该方法返回一个当前时间的 LocalDateTime 对象。具体代码如下:
```
LocalDateTime now = LocalDateTime.now();
```
同时,如果需要获取当前日期的年、月、日等信息,也可以通过 LocalDateTime 对象的 getYear()、getMonthValue()、getDayOfMonth() 等方法来实现。
相关推荐
![text/x-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)