我有一个 java.sql.Timestamp,我想截断日期并以 12 小时制显示它,例如(18:42 为 6:42PM)
我试过:
public static String formatTimestampAsTwelveHour(java.sql.Timestamp stamp){
String stampString = stamp.toString();
String hms = stampString.split(" ")[1];
String[] hmsArray = hms.split(":");
int hours = Integer.parseInt(hmsArray[0]);
int minutes = Integer.parseInt(hmsArray[1]);
int seconds = Integer.parseInt(hmsArray[2]);//just in case someone wants seconds
String suffix = "";
if (hours > 12){
hours = hours -12;
suffix = "PM";
}else if (hours == 12){
suffix = "PM";
}else{
suffix = "AM";
}
String lessThanTen = "";
if (minutes<10){
lessThanTen = "0";
}
return String.format("%i:%s%i %s", hours, lessThanTen,minutes, suffix);
}
我得到(线程“Thread-14”java.lang.NumberFormatException 中的异常:输入字符串:“06.0”)但我从不给它一个十进制数。
最佳答案
SimpleDateFormat做你想做的。
DateFormat format = new SimpleDateFormat( "h:mm a" );
String str = format.format( timestamp );
编辑:其他人发布的格式中带有“K”的版本将返回 0-11 之间的小时数。这将返回 1-12,这更有可能是您想要的。
关于java - 如何将 java.sql.Timestamp 格式化为 (hh :mm AM/PM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5329544/