java获取当天时间并转化为yyyy-mm
时间: 2024-05-16 11:14:03 浏览: 11
-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"。
java yyyymmdd转化为yyyy-mm-dd
你可以使用 SimpleDateFormat 类来将 "yyyymmdd" 格式的日期转换为 "yyyy-mm-dd" 格式的日期。以下是一个示例代码:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
String inputDate = "20211231";
String outputPattern = "yyyy-MM-dd";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
try {
Date date = inputFormat.parse(inputDate);
String outputDate = outputFormat.format(date);
System.out.println(outputDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们将输入日期字符串定义为 "20211231",输出日期格式定义为 "yyyy-MM-dd"。然后,我们使用 SimpleDateFormat 类的 parse() 方法将输入日期字符串解析为 Date 对象。接下来,我们使用 format() 方法将 Date 对象格式化为指定的输出日期格式,并将结果打印出来。在本例中,输出将是 "2021-12-31"。
请注意,这个例子假设输入日期字符串的格式是正确的,并且不包含任何格式错误。如果输入的日期字符串格式不正确,将会抛出 ParseException 异常。你可以根据需要进行错误处理。
相关推荐
![](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)