如何在Android中将HH:mm:ss转换为hh:mm AM / PM

Cha*_*ary 1 datetime android

从Web服务接收的时间为23:30:00。我想将其转换为12小时格式。我想要输出类似11:30 PM的内容(转换23:30:00之后)。

Yug*_*esh 5

使用SimpleDateFormat从一种时间/日期格式转换为另一种。

Log.v("12HRS Time", getFormatedDateTime("23:30:00", "HH:mm:ss", "hh:mm a"))

public static String getFormatedDateTime(String dateStr, String strReadFormat, String strWriteFormat) {

    String formattedDate = dateStr;

    DateFormat readFormat = new SimpleDateFormat(strReadFormat, Locale.getDefault());
    DateFormat writeFormat = new SimpleDateFormat(strWriteFormat, Locale.getDefault());

    Date date = null;

    try {
        date = readFormat.parse(dateStr);
    } catch (ParseException e) {
    }

    if (date != null) {
        formattedDate = writeFormat.format(date);
    }

    return formattedDate;
}
Run Code Online (Sandbox Code Playgroud)

对于SimpleDateFormat参考:-https : //developer.android.com/reference/java/text/SimpleDateFormat.html