使用@JsonFormat 与 Jackson 自定义 DateTime,例如 30/06/2020 08:27 p。米
Custom DateTime with Jackson using @JsonFormat like 30/06/2020 08:27 p. m
我收到了 30/06/2020 08:27 p. m.
这样的日期时间,但问题是 Jackson API 不能用 dd/MM/yyyy hh:mm a
模式反序列化它,因为有点。
我需要模式方面的帮助。
解析前将p. m.
替换为pm
,将a. m.
替换为am
。
演示:
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(final String[] args) throws ParseException {
String strDateTime = "30/06/2020 08:27 p. m.";
// Replace p. m. with pm and a. m. with am
strDateTime = strDateTime.replace("p. m.", "pm").replace("a. m.", "am");
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a");
// Parse the date-time string to LocalDateTime
LocalDateTime ldt = LocalDateTime.parse(strDateTime, formatter);
// Display ldt.toString()
System.out.println(ldt);
// Getting the date-time string back from LocalDateTime object
String backToString = ldt.format(formatter);
System.out.println(backToString);
}
}
输出:
2020-06-30T20:27
30/06/2020 08:27 pm
我收到了 30/06/2020 08:27 p. m.
这样的日期时间,但问题是 Jackson API 不能用 dd/MM/yyyy hh:mm a
模式反序列化它,因为有点。
我需要模式方面的帮助。
解析前将p. m.
替换为pm
,将a. m.
替换为am
。
演示:
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(final String[] args) throws ParseException {
String strDateTime = "30/06/2020 08:27 p. m.";
// Replace p. m. with pm and a. m. with am
strDateTime = strDateTime.replace("p. m.", "pm").replace("a. m.", "am");
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a");
// Parse the date-time string to LocalDateTime
LocalDateTime ldt = LocalDateTime.parse(strDateTime, formatter);
// Display ldt.toString()
System.out.println(ldt);
// Getting the date-time string back from LocalDateTime object
String backToString = ldt.format(formatter);
System.out.println(backToString);
}
}
输出:
2020-06-30T20:27
30/06/2020 08:27 pm