目标:
输入值:“
Feb 26, 2022 1:56 PM
”
获取上述输入值的等效日期时间值,格式为
"yyyy-mm-dd hh:mm:ss"
预期结果:
2022-02-26 13:56:00
我试过的代码:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
class convertDateTime{
public static void main(String[] args) throws Exception{
SimpleDateFormat inputFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm a");
Date date;
date = inputFormat.parse("Feb 26, 2022 1:56 PM");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(outputFormat.format(date));
}
}
运行上述程序时得到的输出(不正确):
2022-02-26 01:56:00
我错过了什么?
你使用了错误的格式。在 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html 上查看详细信息。以下是运行代码。
public static void main(String[] args) throws Exception {
SimpleDateFormat inputFormat = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
Date date = inputFormat.parse("Feb 26, 2022 1:56 PM");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(outputFormat.format(date));
}
输出
2022-02-26 13:56:00
您的第一个格式需要使用
hh
而不是 HH
,因为这被定义为“上午/下午的小时”(参见 JavaDoc)。
public static void main(String[] args) throws Exception{
SimpleDateFormat inputFormat = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
Date date;
date = inputFormat.parse("Feb 26, 2022 1:56 PM");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(outputFormat.format(date));
}