Java 日期格式转换: 将 'Jan 13, 2023' 转换为 '2023-01-13'
可以使用 SimpleDateFormat 类来实现日期格式的转换。下面是一个示例代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String inputDate = 'Jan 13, 2023';
String outputFormat = 'yyyy-MM-dd';
String outputDate = convertDateFormat(inputDate, outputFormat);
System.out.println(outputDate);
}
public static String convertDateFormat(String inputDate, String outputFormat) {
SimpleDateFormat inputDateFormat = new SimpleDateFormat('MMM dd, yyyy');
SimpleDateFormat outputDateFormat = new SimpleDateFormat(outputFormat);
try {
Date date = inputDateFormat.parse(inputDate);
return outputDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
上述代码中,convertDateFormat 方法接受两个参数:inputDate 是输入日期字符串,outputFormat 是期望的输出日期格式。在方法中,我们首先创建了一个 SimpleDateFormat 对象 inputDateFormat,用于解析输入日期字符串。然后,我们创建了另一个 SimpleDateFormat 对象 outputDateFormat,用于格式化输出日期。接下来,我们通过 inputDateFormat.parse(inputDate) 将输入日期字符串解析为 Date 对象,然后使用 outputDateFormat.format(date) 将 Date 对象格式化为输出日期字符串。最后,我们将输出日期字符串返回。
在上述示例中,输入日期字符串 'Jan 13, 2023' 被转换为 '2023-01-13'。可以根据需要修改输入日期字符串和输出日期格式来实现不同的转换。
原文地址: https://www.cveoy.top/t/topic/egb6 著作权归作者所有。请勿转载和采集!