Convert time value to format “hh:mm Am/Pm” using Android

前端 未结 10 1964
粉色の甜心
粉色の甜心 2020-11-28 13:10

I am getting date value from database like \"2013-02-27 06:06:30\" using StringTokenizer I will get time separately like below

String startTime = \"2013-02         


        
10条回答
  •  星月不相逢
    2020-11-28 13:43

    1 Assuming you need to show the current time in the format 09:30 PM. This would be a fairly easy approach. Even if you don't require it for the current time, you should be able to use the below DateFormat for your requirement.

    Calendar cal = Calendar.getInstance();
    DateFormat outputFormat = new SimpleDateFormat("KK:mm a");
    String formattedTime = outputFormat.format(cal.getTime());
    

    2 Note: The following formatter can be used to display the same time in 24-hour format (21:30).

    new SimpleDateFormat("HH:mm");
    

    3 However, if you want to construct the same format as in my first point, it is best to use the following code as Java discourages the use of StringTokenizer. You can read about it here, http://docs.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html

    Hope this would help you, thanks!

        String startTime = "2013-02-27 21:06:30";
        String[] parts = startTime.split(" ");
    
        DateFormat outputFormat = new SimpleDateFormat("KK:mm a");
        SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss");
    
    
        try {
            Date dt = parseFormat.parse(parts[1]);
            System.out.println(outputFormat.format(dt));
        } catch(ParseException exc) {
            exc.printStackTrace();
        }
    

提交回复
热议问题