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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2244444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:17:14  来源:igfitidea点击:

Doubt in getting yesterday's date using java

java

提问by raja

I want to get yesterday's date using java. I have used the following code but it is giving different date each time, Please check whether the code has to be change anywhere. Thanks in advance.

我想使用 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);

This is the output i got when i ran lastly
previous =2010-15-11 00:00:00.000000000
Update date =2011-03-10 00:00:00.0

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

回答by SOA Nerd

The problem is that you're using 'yyyy-mm-dd' which pulls the year-minute-day. Instead use 'yyyy-MM-dd'.

问题是您使用的是“yyyy-mm-dd”,它拉出年-分-日。而是使用“yyyy-MM-dd”。

回答by Valentin Rocher

You used mm in your pattern, so you're using minutes instead of months.

您在模式中使用了 mm,因此您使用的是分钟而不是月。

If you wanna use Joda Time, a simpler date framework, you could do the following :

如果您想使用更简单的日期框架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);

回答by Michael Borgwardt

Your date format pattern string is wrong. "mm" is minutes, "MM" is months. You could have solved this easily by looking at the intermediate results looking like "2010-52-11...".

您的日期格式模式字符串错误。“mm”是分钟,“MM”是月。您可以通过查看类似“2010-52-11...”的中间结果轻松解决这个问题。

回答by Cogsy

Calendar cal = Calendar.getInstance();
cal.roll(Calendar.DATE, false); //you can also use add(int, int)
System.out.println(cal.toString());

All in standard Java since 1.1. Also have a look at GregorianCalendar if you need to. Read the docs to see how it handles daylight savings etc.

自 1.1 起全部采用标准 Java。如果需要,还可以查看 GregorianCalendar。阅读文档以了解它如何处理夏令时等。