java获取当前时间,并转化为时间格式为yyyy-mm-dd的date类型
时间: 2024-04-29 11:26:35 浏览: 10
你好,以下是获取当前时间并转换为指定格式的 Java 代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date currDate = new Date();
String currTime = sdf.format(currDate);
System.out.println(currTime);
}
}
```
这段代码中,我们使用了 SimpleDateFormat 类来定义输出时间的格式,并使用 format() 方法将当前时间转换为指定格式的时间字符串。最后通过 System.out.println() 方法输出。
相关问题
java获取当天时间并转化为yyyy-mm
-dd格式的字符串,可以使用如下代码实现:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = sdf.format(date);
System.out.println(dateString);
}
}
```
这段代码会输出当前日期的字符串,格式为"yyyy-MM-dd",例如"2021-10-15"。你可以根据实际需求修改日期格式。
java yyyymmdd转化为yyyy-mm-dd date
你可以使用Java中的SimpleDateFormat类来实现日期格式的转换。以下是将"yyyymmdd"格式转换为"yyyy-mm-dd"格式的示例代码:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatConverter {
public static void main(String[] args) {
String inputDate = "20211231";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = inputFormat.parse(inputDate);
String outputDate = outputFormat.format(date);
System.out.println(outputDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们首先定义了输入日期的格式为"yyyyMMdd",输出日期的格式为"yyyy-MM-dd"。然后,使用`parse()`方法将输入日期字符串解析为Date对象。最后,使用`format()`方法将Date对象格式化为输出日期字符串"yyyy-MM-dd"。运行上述代码,将输出转换后的日期"2021-12-31"。