返回"关闭时间"的确切字符串从我的json结果下面。它似乎是24小时的时间格式。我做了一点搜索,发现它不是HH:MM:SS所需的格式。什么是将其转换为12小时上午PM时间的有效方法。 Thanks.`
String closingTime = "2100";
//Desired output: String closingTime = "9:00 pm"
答案 0 :(得分:1)
我建议将时间解析为Calendar对象。这使得用给定的时间实际做事很容易,而不是仅仅将其作为字符串处理
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:00 PM"如果你给它" 2100",但内部的数据存储为millis,所以如果你需要,你可以用它做更多的事情。
修改强> 上面的代码不正确,更像是伪代码,正如提问者所说,他提出了以下更完整的代码:
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);
答案 1 :(得分:0)
public static Date getDateFromString(String format, String dateStr) {
DateFormat formatter = new SimpleDateFormat(format);
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/////////////////////
public static String getCurrentDate(String format) {
SimpleDateFormat sdfFrom = new SimpleDateFormat(format);
Calendar currentTime = Calendar.getInstance();
return (sdfFrom.format(currentTime.getTime()));
}