我的字符串日期为“ 04/01 / 2020,9:00PM”。我想将其转换为ISO日期格式。寻找将其转换为ISO日期格式的优化方法
答案 0 :(得分:2)
尝试此代码:
public static void main(String[] args) {
String dateString = "04/01/2020 at 9:00PM";
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy 'at' hh:mma");
try {
Date date = dateFormat.parse(dateString);
System.out.println(date);
} catch(ParseException exception) {
System.out.println(exception.getMessage());
}
}
查看此帖子以获取更多信息:https://stackoverflow.com/a/4216767/10030693
更新
根据Mark Rotteveel的建议,DateTimeFormatter是一种更好的API,可用于在Java 8中格式化日期,因此应首选:
public static void main(String[] args) {
String dateString = "12/12/2020 at 09:00PM";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("d/M/yyyy 'at' hh:mma", Locale.ENGLISH);
try {
LocalDateTime dateTime = LocalDateTime.parse(dateString, dateTimeFormatter);
System.out.println(dateTime);
} catch (DateTimeException exception) {
System.out.println(exception.getMessage());
}
}