怀疑使用java获取昨天的日期

raj*_*aja 2 java

我想用java获取昨天的日期.我使用了以下代码但每次都给出不同的日期,请检查代码是否必须在任何地方更改.提前致谢.

 SimpleDateFormat formatter= 
        new SimpleDateFormat("yyyy-mm-dd ");
    Calendar currentDate = Calendar.getInstance();
    String previous = formatter.format(currentDate.getTime())+ "00:00:00.000000000";
    System.out.println("previous ="+previous);
    currentDate.add(Calendar.DATE, -1);
    String previousDate = formatter.format(currentDate.getTime())+ "00:00:00.000000000";
    Timestamp updateTimestamp = Timestamp.valueOf(previousDate);
    System.out.println("Update date ="+updateTimestamp);
Run Code Online (Sandbox Code Playgroud)

这是我最后一次运行时得到的输出
= 2010-15-11 00:00:00.000000000
更新日期= 2011-03-10 00:00:00.0

SOA*_*erd 15

问题是你正在使用'yyyy-mm-dd'来拉动年度分钟日.而是使用'yyyy-MM-dd'.


Val*_*her 10

你在模式中使用mm,所以你使用的是分钟而不是几个月.

如果您想使用Joda Time,一个更简单的日期框架,您可以执行以下操作:

DateTimeFormat format = DateTimeFormat.forPattern("yyyy-MM-dd 00:00:00.000000000");
DateTime now = new DateTime();
System.out.println("Previous :" + format.print(now);
DateTime oneDayAgo = now.minusDays(1);
System.out.println("Updated :" + format.print(oneDayAgo);
Run Code Online (Sandbox Code Playgroud)


Mic*_*rdt 6

您的日期格式模式字符串是错误的."mm"是分钟,"MM"是几个月.你可以通过查看看起来像"2010-52-11 ..."的中间结果轻松解决这个问题.