直接了当:
SimpleDateFormat formatTime = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss aa", Locale.ENGLISH);
注意:hh:mm:ss 不能是HH:mm:ss
如果是HH:
正确的结果应该是:2019-03-03 07:10:10 PM
反过来解析我们解析需要注意:
解析时需要使用 hh,而在格式到我们需要的时候,我们需要使用 HH !!!!
最后提供方法:
public static String getAMorPMFormatTime(String time, String format){
SimpleDateFormat formatTime = new SimpleDateFormat(format + " aa", Locale.ENGLISH);
try {
return formatTime.format(new SimpleDateFormat(format).parse(time));
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
System.out.println(getAMorPMFormatTime("2019-03-03 19:10:10", "yyyy-MM-dd hh:mm:ss"));
System.out.println(getTimeByAMorPMFormat("2019-03-03 07:10:10 PM", "yyyy-MM-dd hh:mm:ss"));
}
public static String getTimeByAMorPMFormat(String time, String format){
SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa", Locale.ENGLISH);
SimpleDateFormat formatTime1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = "";
try {
str = formatTime1.format(formatTime.parse(time));
} catch (Exception e) {
System.out.println("传入日期错误");
}
return str;
}
AM数字值区间:01:00:00 - 12:59:59
PM数字值区间:01:00:00 - 12:59:59
当初为了弄懂这个花了不少时间!跟我认为的逻辑不一样的是:
1.我认为超过12:00:00(上午/下午)就应该是00:00:01 PM/AM.........
2.但是AM个PM没有00:00:00-01:00:00区间。