开发者

How do I format a java.sql.Timestamp as (hh:mm AM/PM)

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.p开发者_C百科arseInt(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.


SimpleDateFormat does what you want.

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.


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


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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜