从
SimpleDateFormat开始,这将允许您解析和格式化时间值,例如……
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
try {
// Get the start time..
Date start = sdf.parse("09:00 AM");
System.out.println(sdf.format(start));
} catch (ParseException ex) {
ex.printStackTrace();
}
有了这个,您就可以使用Calendar来操作日期值的各个字段……
Calendar cal = Calendar.getInstance();
cal.setTime(start);
cal.add(Calendar.MINUTE, 45);
Date end = cal.getTime();
把它们放在一起……
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
try {
Date start = sdf.parse("09:00 AM");
Calendar cal = Calendar.getInstance();
cal.setTime(start);
cal.add(Calendar.MINUTE, 45);
Date end = cal.getTime();
System.out.println(sdf.format(start) + " to " + sdf.format(end));
} catch (ParseException ex) {
ex.printStackTrace();
}
输出时间为09:00 AM至09:45 AM
更新
或者你可以使用JodaTime ……
DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendHourOfDay(2).appendLiteral(":").appendMinuteOfHour(2).appendLiteral(" ").appendHalfdayOfDayText().toFormatter();
LocalTime start = LocalTime.parse("09:00 am", dtf);
LocalTime end = start.plusMinutes(45);
System.out.println(start.toString("hh:mm a") + " to " + end.toString("hh:mm a"));
或者,如果您使用的是Java 8,那么新的日期/时间API ……
DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("hh:mm a").toFormatter();
LocalTime start = LocalTime.of(9, 0);
LocalTime end = start.plusMinutes(45);
System.out.println(dtf.format(start) + " to " + dtf.format(end));