java把yyyy/mm/dd变成yyyy-mm-dd
可以使用 SimpleDateFormat 类中的 format 方法将日期格式从 yyyy/mm/dd 转换为 yyyy-mm-dd。具体代码如下:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter {
public static void main(String[] args) {
String dateString = "2022/01/01";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = inputFormat.parse(dateString);
String outputDateString = outputFormat.format(date);
System.out.println(outputDateString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果为:2022-01-01。
Java 入参如果是自动判断是yyyy/MM/dd、yyyy/MM/dd HH:mm:ss、yyyy-MM-dd类型,都转换成 yyyy-MM-dd
在Java中,可以使用SimpleDateFormat类来进行日期格式的转换。针对不同的日期格式,可以通过以下步骤来实现统一转换成"yyyy-MM-dd"格式:
首先,创建一个SimpleDateFormat对象,指定输入日期格式的模式。例如,对于"yyyy/MM/dd"格式,可以使用以下代码创建SimpleDateFormat对象:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
然后,使用SimpleDateFormat对象的parse()方法将输入的日期字符串解析为Date对象。例如:
Date date = inputFormat.parse(inputDateString);
接下来,创建另一个SimpleDateFormat对象,指定输出日期格式的模式为"yyyy-MM-dd"。例如:
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
最后,使用SimpleDateFormat对象的format()方法将Date对象格式化为指定的输出日期字符串。例如:
String outputDateString = outputFormat.format(date);
通过以上步骤,无论输入的日期字符串是"yyyy/MM/dd"、"yyyy/MM/dd HH:mm:ss"还是"yyyy-MM-dd"格式,都可以统一转换成"yyyy-MM-dd"格式的输出日期字符串。
怎么用Java将yyyy-mm-dd改成yyyy/mm/dd
可以使用Java中的SimpleDateFormat类来解决这个问题。
以下是一个示例代码:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
String inputDate = "2022-07-01";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy/MM/dd");
try {
Date date = inputFormat.parse(inputDate);
String outputDate = outputFormat.format(date);
System.out.println("Input Date : " + inputDate);
System.out.println("Output Date : " + outputDate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上面的代码中,我们首先定义了一个输入日期字符串和两个SimpleDateFormat对象。第一个对象用于解析输入日期字符串,第二个对象用于格式化输出日期字符串。
然后,我们使用try-catch块来捕获可能的异常,并使用format()方法将日期对象格式化为输出字符串。
在控制台中运行上面的代码将得到以下输出:
Input Date : 2022-07-01
Output Date : 2022/07/01
可以看到,输入日期字符串已成功转换为指定格式的输出日期字符串。
相关推荐
















