我正在使用這段代碼:
final String OLD_FORMAT = "dd-MMM-yy";
final String NEW_FORMAT = "dd/MM/yyyy";
String oldDateString = "16-OCT-19";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
System.out.println(newDateString);
是否可以在不轉換為Date
first 的情況下進行轉換,因此我們看不到 ( OLD_FORMAT
) 之前的格式?
我有一個可以是任何格式日期的字串。例如"dd-MM-yyyy"
, "dd-MMM-yyyy"
, "dd-MMMM-yyyy"
, 或任何東西。我想格式化成特定的格式 date "dd/MM/yyyy"
。
uj5u.com熱心網友回復:
您不能使用內置類。您可以圍繞它創建自己的包裝器以這種方式作業。
class MultipleDateFormat {
private List<SimpleDateFormat> formatList;
MultipleDateFormat(String... formats) {
formatList = Arrays.asList(formats);
}
public Date parse(String dateString) throws Exception {
for (SimpleDateFormat format : formatList) {
try {
return format.parse(dateString);
} catch (Exception ex) {
continue;
}
}
throw Exception("String cannot be parsed");
}
}
使用它來創建多種格式的實體。
MultipleDateFormat formats = new MultipleDateFormat(format1, format2, . .);
Date date = formats.parse(oldDateString);
uj5u.com熱心網友回復:
您絕對可以使用利用可能或預期模式串列的方法,并為每個模式分配 a try
,但您應該使用最優化的庫,而不是由于大量遺留代碼參考它而仍然存在的庫。
tl;dr
你的朋友(從 Java 8 開始)是
java.time.LocalDate
java.time.format.DateTimeFormatter
java.time.format.DateTimeFormatterBuilder
java.time.format.DateTimeParseException
這是一個例子:
public static void main(String[] args) {
// start with an example String
String oldDateString = "16-OCT-19";
// build up a list of possible / possibly expected patterns
List<String> patterns = List.of(
"dd-MM-uu", "dd-MMM-uu", "dd-MMMM-uu",
"dd-MM-uuuu", "dd-MMM-uuuu", "dd-MMMM-uuuu"
);
// then build a formatter for the desired output
DateTimeFormatter outFmt = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// for each pattern in your list
for (String pattern : patterns) {
try {
// build a formatter that
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
// doesn't care about case
.parseCaseInsensitive()
// uses the current pattern and
.appendPattern(pattern)
// considers the language/locale
.toFormatter(Locale.ENGLISH);
// then try to parse the String with that formatter and
LocalDate localDate = LocalDate.parse(oldDateString, dtf);
// print it using the desired output formatter
System.out.println(localDate.format(outFmt));
// finally stop the iteration in case of success
break;
} catch (DateTimeParseException dtpEx) {
// build some meaningful statements
String msg = String.format(
"%s !\n ——> you cannot parse '%s' using pattern %s",
dtpEx.getMessage(), oldDateString, pattern);
// and print it for each parsing fail
System.err.println(msg);
}
}
}
嘗試使用不同的輸入,并可能擴展模式串列。
但是,此代碼示例對于串列中的第一個模式失敗,但第二個是匹配的,因此列印
Text '16-OCT-19' could not be parsed at index 3 !
——> you cannot parse '16-OCT-19' using pattern dd-MM-uu
16/10/2019
剩余的模式被跳過。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496837.html