更改日期格式Java



我正在使用这个代码:

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的情况下进行转换,这样我们就不会在(OLD_FORMAT)之前看到格式?

我有一个字符串,可以是任何格式的日期。例如:"dd-MM-yyyy","dd-MMM-yyyy","dd-MMMM-yyyy",或者其他任意值。我想要格式化为特定的格式日期"dd/MM/yyyy"

不能使用内置类。您可以在它周围创建自己的包装器以这种方式工作。

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);

你当然可以使用这种方法,利用一个可能的或预期的模式列表,并给每个模式一个try,但你应该使用最优化的库,而不是一个由于大量遗留代码引用它而仍然有效的库。

tl;博士
这个任务的好友(从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

其余模式将被跳过。

最新更新