java 小时时间就近取整

/**
* 时间就近取整
* 08:00 -> 08:00,
* 08:20 -> 08:30,
* 08:30 -> 08:30,
* 08:45 -> 09:00,
* 23:56 -> 00:00
*
* @param time
* @return outTime
*/
public static String getCompleteTime(String time) {
String hour = "00";//小时
String minutes = "00";//分钟
String outTime = "00:00";
StringTokenizer st = new StringTokenizer(time, ":");
List<String> inTime = new ArrayList<String>();
while (st.hasMoreElements()) {
inTime.add(st.nextToken());
}
hour = inTime.get(0).toString();
minutes = inTime.get(1).toString();
if (Integer.parseInt(minutes) > 30) {
hour = (Integer.parseInt(hour) + 1) + "";
outTime = hour + ":00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
try {
outTime = sdf.format(sdf.parse(outTime));
} catch (Exception e) {
e.printStackTrace();
}
} else if (Integer.parseInt(minutes) == 00) {
outTime = hour + ":00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
try {
outTime = sdf.format(sdf.parse(outTime));
} catch (Exception e) {
e.printStackTrace();
}
} else if (Integer.parseInt(minutes) <= 30 && Integer.parseInt(minutes) != 00) {
outTime = hour + ":30";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

try {
outTime = sdf.format(sdf.parse(outTime));
} catch (Exception e) {
e.printStackTrace();
}
}
return outTime;
}
posted @ 2020-04-01 12:21  zhangheliang  阅读(312)  评论(0编辑  收藏