如何将 java.sql.Timestamp 格式化为 (hh:mm AM/PM)
我有一个 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”)但我从不给它一个十进制数。
I have a java.sql.Timestamp and I would like to cut off the date and show it in 12 hour fashion, eg (18:42 as 6:42PM)
I tried:
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);
}
I get (Exception in thread "Thread-14" java.lang.NumberFormatException: For input string: "06.0") but I never give it a decimal number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SimpleDateFormat 可以满足您的需求。
编辑:其他人发布的格式中带有“K”的版本将返回 0-11 之间的小时数。这将返回 1-12,这更有可能是您想要的。
SimpleDateFormat does what you want.
Edit: The version someone else posted with "K" in the format will return hours between 0-11. This will return 1-12, which is more likely to be what you want.
您不需要自己解析它,您可以使用
SimpleDateFormat
和"h:mm a"
因为它是java.util.Date< 的子类/代码>
You don't need to parse it yourself, you can use
SimpleDateFormat
and"h:mm a"
as it is a subclass ofjava.util.Date
Java 已经提供了日期格式化例程,而且很可能它们比您独立编写的任何实现都更好、更快。
此外,您确实需要从时间戳的毫秒值创建一个 java.util.Date ,因为在特定的实现中,当您尝试通过其 Date 父类格式化时间戳时,我注意到毫秒发生了奇怪的事情。
Java already provides date formatting routines, and odds are they are a better and faster implementation than anything you'll cook up independently.
In addition, you do need to create a java.util.Date from the Timestamp's millisecond value, as in particular implementations I've noticed strange things happening with the milliseconds when you attempt to format a Timestamp via it's Date parent class.