如何将 java.sql.Timestamp 格式化为 (hh:mm AM/PM)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5329544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I format a java.sql.Timestamp as (hh:mm AM/PM)
提问by davidahines
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)
我有一个 java.sql.Timestamp,我想截断日期并以 12 小时的方式显示它,例如(18:42 为 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.
我得到(线程“Thread-14”中的异常java.lang.NumberFormatException:对于输入字符串:“06.0”)但我从来没有给它一个十进制数。
回答by Calum
SimpleDateFormatdoes what you want.
SimpleDateFormat做你想要的。
DateFormat format = new SimpleDateFormat( "h:mm a" );
String str = format.format( timestamp );
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.
编辑:其他人以“K”格式发布的版本将返回 0-11 之间的小时数。这将返回 1-12,这更有可能是您想要的。
回答by Edwin Buck
public static String formatTimestampAsTwelveHour(java.sql.Timestamp stamp){
java.util.Date date = new Date(stamp.getTime());
SimpleDateFormat format = new SimpleDateFormat("your format here");
return format.format(date);
}
Java already provides date formatting routines, and odds are they are a better and faster implementation than anything you'll cook up independently.
Java 已经提供了日期格式化例程,而且很可能它们是比您独立编写的任何东西都更好、更快的实现。
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.
此外,您确实需要从时间戳的毫秒值创建一个 java.util.Date,因为在特定的实现中,我注意到当您尝试通过它的 Date 父类格式化时间戳时,毫秒会发生奇怪的事情。
回答by z7sg ?
You don't need to parse it yourself, you can use SimpleDateFormat
and "h:mm a"
as it is a subclass of java.util.Date
您不需要自己解析它,您可以使用SimpleDateFormat
and"h:mm a"
因为它是java.util.Date