英文:
Increment time with 12 hour clock from AM to PM
问题
我正在尝试增加一个时间值,并得到了奇怪的结果:
private String getNextTime(String time) {
final int INTERVAL = 1;
SimpleDateFormat df = new SimpleDateFormat("HH:mm a", Locale.US);
Date d = null;
try {
d = df.parse(time);
} catch (ParseException e) {
System.out.println("Bad tee time: " + time);
System.exit(-1);
}
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, INTERVAL);
String outTime = df.format(cal.getTime());
return (outTime);
}
如果我输入11:59 AM,结果是12:00 PM。如果我输入12:59 PM,我期望得到01:00 PM,但却得到了13:00 PM。如果我输入01:00 PM,我期望得到01:01 PM,但却得到了01:01 AM。如何使它在12小时制下正确工作?
英文:
I am trying to increment a time value and getting odd results:
private String getNextTime(String time) {
final int INTERVAL = 1;
SimpleDateFormat df = new SimpleDateFormat("HH:mm a", Locale.US); /
Date d = null;
try {
d = df.parse(time);
} catch (ParseException e) {
System.out.println("Bad tee time: " + time);
System.exit(-1);
}
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, INTERVAL);
String outTime = df.format(cal.getTime());
return (outTime);
}
If I input 11:59 AM the result is 12:00PM. If I input 12:59 PM I am expecting 01:00 PM, but get 13:00 PM. If I input 01:00 PM, I am expecting 01:01 PM, but get 01:01 AM. How do I get this to work correctly with a 12 hour clock?
答案1
得分: 1
SimpleDateFormat和Date已经过时且存在缺陷。请使用更现代的类来自java.time包。
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:mm a", Locale.US));
LocalTime ldt = LocalTime.of(9, 0);
for (int h = 1; h < 10; h++) {
System.out.println(ldt.format(dtf));
ldt = ldt.plusHours(h);
}
输出结果为:
9:00 AM
10:00 AM
12:00 PM
3:00 PM
7:00 PM
12:00 AM
6:00 AM
1:00 PM
9:00 PM
如果未指定,默认使用默认区域设置(Locale)。如果您希望单个数字小时前面有前导零,请使用"hh:mm a"
。
英文:
SimpleDateFormat and Date are obsolete and buggy. Use the more modern classes from the java.time package.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:mm a", Locale.US));
LocalTime ldt = LocalTime.of(9, 0);
for (int h = 1; h < 10; h++) {
System.out.println(ldt.format(dtf));
ldt = ldt.plusHours(h);
}
prints
9:00 AM
10:00 AM
12:00 PM
3:00 PM
7:00 PM
12:00 AM
6:00 AM
1:00 PM
9:00 PM
Default Locale will be used if not specified. And use "hh:mm a"
if you want leading zeros for single digit hours.
答案2
得分: 0
好的,已翻译如下:
将:
SimpleDateFormat df = new SimpleDateFormat("HH:mm a", Locale.US);
改为:
SimpleDateFormat df = new SimpleDateFormat("hh:mm a", Locale.US);
英文:
Never mind.
Change:
SimpleDateFormat df = new SimpleDateFormat("HH:mm a", Locale.US);
to:
SimpleDateFormat df = new SimpleDateFormat("hh:mm a", Locale.US);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论