共計 1073 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用 SimpleDateFormat
類來進行日期格式的轉換。以下是一個示例代碼,演示了如何將一個日期字符串轉換成另一種日期格式的字符串:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {public static void main(String[] args) {String dateString = "2023-05-15";
String sourceFormat = "yyyy-MM-dd";
String targetFormat = "dd/MM/yyyy";
try {SimpleDateFormat sourceDateFormat = new SimpleDateFormat(sourceFormat);
SimpleDateFormat targetDateFormat = new SimpleDateFormat(targetFormat);
Date date = sourceDateFormat.parse(dateString);
String formattedDateString = targetDateFormat.format(date);
System.out.println(" 原日期字符串:" + dateString);
System.out.println(" 轉換后的日期字符串:" + formattedDateString);
} catch (ParseException e) {e.printStackTrace();
}
}
}
在上面的示例中,首先定義了一個日期字符串 dateString
,其格式為yyyy-MM-dd
。然后,定義了源日期格式sourceFormat
和目標日期格式 targetFormat
。接下來,創建了兩個SimpleDateFormat
對象,用于解析和格式化日期。使用 sourceDateFormat
對象的 parse()
方法將日期字符串解析為 Date
對象。然后,使用 targetDateFormat
對象的 format()
方法將 Date
對象格式化為目標日期格式的字符串。最后,將原日期字符串和轉換后的日期字符串打印出來。
運行上面的代碼,輸出結果如下:
原日期字符串:2023-05-15
轉換后的日期字符串:15/05/2023
這樣就完成了日期格式的轉換。根據實際需求,可以修改源日期格式和目標日期格式,以及要轉換的日期字符串。
丸趣 TV 網 – 提供最優質的資源集合!
正文完