您可以通过 3 种方式做到这一点。首先是使用SimpleDateFormat
and Date
和第二次使用DateTimeFormatter
and LocalDate
第三你可以使用Split
.
1.使用日期和SimpleDateFormat
String date = "11-12-2018";
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);
String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
System.out.println(finalDate);
这是我们的实际日期String date = "11-12-2018";
我们知道我们想把它改成2018-12-11
因此,让我们将该日期解析为Date
使用此代码的对象
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);
好的,现在我们有了实际日期的日期对象,现在让我们将其格式化为新日期。
String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
2.使用LocalDate和DateTimeFormatter
好吧,我们在这里再次定义日期和 2 DateTimeFormatter。
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
第一个格式化程序是我们的旧日期格式,第二个格式化程序是我们要将旧日期转换成的新格式。
好吧,现在就使用它们吧!
现在我们制作一个新的LocalDate
通过解析我们的 oldFormatter 对象dateString
与oldFormatter
object
LocalDate dateTime = LocalDate.parse(date, oldFormatter);
好吧,现在让我们格式化它。
String reformattedDate = dateTime.format(newFormatter);
就如此容易!这是完整的代码。
String date = "11-12-2018";
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(date, oldFormatter);
String reformattedDate = dateTime.format(newFormatter);
System.out.println(reformattedDate);
3. 使用 String::Split
好的,这部分非常简单。让我们使用分割日期-
String[] dates = date.split("-");
我们已经知道日期的顺序,让我们使用以下命令对其进行格式化String::format
String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
这是完整的代码
String date = "11-12-2018";
String[] dates = date.split("-");
String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
System.out.println(reformattedDate);