Java 将24小时时间内的字符串转换为12小时AM PM时间

Java 将24小时时间内的字符串转换为12小时AM PM时间,java,datetime,Java,Datetime,从我的json结果返回下面“关闭时间”的确切字符串。它似乎是24小时的时间格式。我四处搜索了一下,发现它的格式不是HH:MM:SS。什么是将此转换为12小时AM PM时间的有效方法。谢谢` String closingTime = "2100"; //Desired output: String closingTime = "9:00 pm" 我建议将时间解析为日历对象。这使得在给定的时间内实际执行任务变得非常容易,而不仅仅是将其作为字符串处理 Calendar time = Calendar

从我的json结果返回下面“关闭时间”的确切字符串。它似乎是24小时的时间格式。我四处搜索了一下,发现它的格式不是HH:MM:SS。什么是将此转换为12小时AM PM时间的有效方法。谢谢`

String closingTime = "2100";
//Desired output: String closingTime = "9:00 pm"

我建议将时间解析为日历对象。这使得在给定的时间内实际执行任务变得非常容易,而不仅仅是将其作为字符串处理

Calendar time = Calendar.getInstance();

//Calendar.HOUR_OF_DAY is in 24-hour format
time.set(Calendar.HOUR_OF_DAY, closingTime.substring(0,2));

time.set(Calendar.MINUTE, closingTime.substring(2,4));

//Calendar.HOUR is in 12-hour format
System.out.print(time.get(Calendar.HOUR) + ":" + time.get(Calendar.MINUTE) + " " + time.get(Calendar.AM_PM));
上面的代码将打印出“9:00pm”,如果你给它“2100”,但数据内部存储为毫秒,所以你可以做更多,如果你需要它

编辑 上面的代码不正确,更像是伪代码,正如提问者所指出的,他建议使用以下更完整的工作代码:

String closingTime = "2101";
//getInstance() will return the current millis, so changes will be made relative to the current day and time
Calendar time = Calendar.getInstance();
// Calendar.HOUR_OF_DAY is in 24-hour format
time.set(Calendar.HOUR_OF_DAY, Integer.parseInt(closingTime.substring(0, 2)));

// time.get(Calendar.MINUTE) returns the exact minute integer e.g for 10:04 will show 10:4
// For display purposes only We could just return the last two substring or format Calender.MINUTE as shown below
time.set(Calendar.MINUTE, Integer.parseInt(closingTime.substring(2, 4)));
String minute = String.format("%02d", time.get(Calendar.MINUTE));

// time.get(Calendar.AM_PM) returns integer 0 or 1 so let's set the right String value
String AM_PM = time.get(Calendar.AM_PM) == 0 ? "AM" : "PM";

// Calendar.HOUR is in 12-hour format
System.out.print("...\n" + time.get(Calendar.HOUR) + ":" + minute + " " + AM_PM);
/////////////////////

public static String getCurrentDate(String format) {
        SimpleDateFormat sdfFrom = new SimpleDateFormat(format);
        Calendar currentTime = Calendar.getInstance();
        return (sdfFrom.format(currentTime.getTime()));
    }

那么
“2100”
的期望输出是什么?期望输出是晚上9点。谢谢你所说的
所需的HH:MM:SS格式是什么意思?2100是晚上9点,修正为晚上9点。那是个打字错误。我想那应该是军事时间。我找到的大多数解决方案都显示了从该格式到12小时时间格式的转换。接受的答案也很好,但您的方法最有用,因为时间正在转换为日历对象。我还有一些补充。我会在你答案的正下方编辑。非常感谢。
public static String getCurrentDate(String format) {
        SimpleDateFormat sdfFrom = new SimpleDateFormat(format);
        Calendar currentTime = Calendar.getInstance();
        return (sdfFrom.format(currentTime.getTime()));
    }