我希望在给定日期增加一天。如果我通过了2018-08-05,则以下方法将返回2018-08-06,这是预期的。但是,如果通过月份的最后日期-2018-08-31,则返回2018-08-01,而不是预期的结果2018-09-01。
DateFormat format = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
Date date = null;
try {
date = format.parse("2018-08-31");
} catch (ParseException e) {
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE ,1);
return format.format(cal.getTime());
答案 0 :(得分:5)
您正在使用旧的日历/日期API。该API相当糟糕(它做的事情很奇怪,并且无法准确地模拟日期的实际工作方式。)
它已被新的java.time API取代。我强烈建议您改用它。如果您使用的是Java7或更低版本,则可以在依赖列表中使用“ JSR310-backport”库来使用此API。 (JSR310是此Java添加名称)。
在java.time中,您可以这样做:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse("2018-08-31", fmt);
System.out.println(fmt.format(date.plusDays(1)));
// yyyy-MM-dd so happens to be the default for LocalDate, so...
// we can make it a lot simpler:
date = LocalDate.parse("2018-08-31");
System.out.println(date.plusDays(1));
}
}
答案 1 :(得分:0)
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date = null;
try {
date = format.parse("2018-08-31");
} catch (ParseException e) {
}
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.setTimeInMillis(cal.getTimeInMillis() + 86400000); //86400000ms = 1 day
return format.format(cal.getTime());
答案 2 :(得分:0)
该错误出现在import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
# The objects consist of a pygame.Rect, the y-speed and a color.
objects = [
[pygame.Rect(150, -20, 64, 30), 5, pg.Color('dodgerblue')],
[pygame.Rect(350, -20, 64, 30), 3, pg.Color('sienna1')],
]
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
for obj in objects:
# [0] is the rect, [1] is the y-speed.
# Move the objects by adding the speed to the rect.y coord.
obj[0].y += obj[1]
screen.fill(BG_COLOR)
# Draw the rects.
for obj in objects:
pg.draw.rect(screen, obj[2], obj[0])
pg.display.flip()
clock.tick(60)
pg.quit()
的模式中,用于输入和输出。这种双重用途掩盖了错误:
SimpleDateFormat
这给您:
public class Main {
public static void main(String[] args) throws Exception {
DateFormat format = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
Date date = format.parse("2018-08-31");
System.out.println("format: " + format.format(date) +", real: " + date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE ,1);
System.out.println("format: " + format.format(cal.getTime()) +", real: " + cal.getTime());
}
}
使用正确的模式format: 2018-08-31, real: Wed Jan 31 00:08:00 CET 2018
format: 2018-08-01, real: Thu Feb 01 00:08:00 CET 2018
会得出正确的答案:
yyyy-MM-dd
由于新的和旧的Java-Time API使用相同的模式,因此在这种情况下仅采用新的API将无济于事。