如何将java.sql.Timestamp格式化为(hh:mm AM / PM)

时间:2011-03-16 17:53:08

标签: java parsing time timestamp clock

我有一个java.sql.Timestamp,我想切断日期并以12小时的方式显示,例如(18:42 as 6:42 PM)

我试过了:

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”)但我从不给它一个十进制数。

3 个答案:

答案 0 :(得分:11)

SimpleDateFormat做你想做的事。

DateFormat format = new SimpleDateFormat( "h:mm a" );
String str = format.format( timestamp );

编辑:其他人在格式中以“K”发布的版本将返回0-11之间的小时数。这将返回1-12,这更有可能是你想要的。

答案 1 :(得分:2)

您无需自行解析,可以使用SimpleDateFormat"h:mm a",因为它是java.util.Date

的子类

答案 2 :(得分:2)

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已经提供了日期格式化例程,而且它们的实现速度比你独立完成的任何东西都要好。

此外,您需要从Timestamp的毫秒值创建一个java.util.Date,因为在特殊实现中,当您尝试通过它的Date父类格式化时间戳时,我注意到发生了奇怪的事情。

相关问题