java 获取今天时间的Data
时间: 2023-10-20 22:19:14 浏览: 44
可以使用以下代码获取今天时间的Data:
```java
Date today = new Date();
```
或者使用以下代码获取指定日期的Data:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("2021-12-01");
```
相关问题
java data获取当前时间
Java中获取当前时间有两种常用的方法,分别是使用Date类和Calendar类。其中,Date类是表示日期和时间的类,而Calendar类则是一个抽象类,提供了许多操作日期和时间的方法。
使用Date类获取当前时间的代码如下:
```
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(date));
```
其中,第一行代码创建了一个Date对象,表示当前系统时间;第二行代码创建了一个SimpleDateFormat对象,用于格式化输出时间;第三行代码调用format()方法将Date对象转换为指定格式的字符串,并输出。
使用Calendar类获取当前时间的代码如下:
```
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH) + 1;
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
System.out.println(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);```
其中,第一行代码创建了一个Calendar对象,表示当前系统时间;接下来的几行代码分别获取年、月、日、时、分、秒,并输出。
java获取系统时间转换成dataformat
您可以使用`java.util.Date`类和`java.text.SimpleDateFormat`类来获取系统时间并将其转换为指定的格式。
以下是一个示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
// 获取系统当前时间
Date currentDate = new Date();
// 定义日期格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将日期转换为指定格式的字符串
String formattedDate = dateFormat.format(currentDate);
System.out.println("当前时间:" + formattedDate);
}
}
```
在上述示例中,我们首先使用`new Date()`创建一个表示当前时间的`Date`对象。然后,我们使用`SimpleDateFormat`类来定义日期的格式,这里使用的是"yyyy-MM-dd HH:mm:ss"表示年-月-日 时:分:秒的格式。最后,我们通过调用`format()`方法将`Date`对象转换为指定格式的字符串,并将其打印输出。
运行上述代码,您将获得类似以下格式的当前时间:
```
当前时间:2022-01-01 10:30:45
```
您可以根据需要调整日期格式的定义。
相关推荐
![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)