Calendar to Date 问题,期间有 1 年错误

Calendar to Date issue, period with 1 year error

这是我第一次问,我在网上找不到解释,所以你去: 我正在编写一个简单的函数来计算 x 天前的日期,所以我编写了这段工作正常的代码,直到今天,计算的过去日期是未来 1 年,但不是所有的值,只有11天前,其他都还好。 如果您今天执行此代码,您将获得以下输出:you can execute it here

difference:-11

2015-12-28

difference:-12

2014-12-27

如您所见,我虽然从 Calendar 解析到 Date 时遇到问题,但我也检查过 Calendar 中的值完全没问题,但是当我转移到 Date 时它不起作用,我尝试手动执行此转换,但不推荐使用这些功能。

import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(getDate(-11, "YYYY-MM-dd"));
        System.out.println(getDate(-12, "YYYY-MM-dd"));
    }
    public static String getDate(int offset, String SimpleFormat) {
        DateFormat dateFormat = new SimpleDateFormat(SimpleFormat);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, offset);
        Date todate1 = cal.getTime();
        long diff = todate1.getTime()-(new Date()).getTime();
        System.out.println("difference:"+diff/ (24 * 60 * 60 * 1000));
        String fromdate = dateFormat.format(todate1);
        return fromdate;
    }
}    

后来我发现了一个不错的库,叫做 Joda-Time 非常好用而且速度很快,所以我更改了代码来使用它,但还是遇到了同样的问题。

DateFormat dateFormat = new SimpleDateFormat(SimpleFormat);
DateTime today = new DateTime();
String fromdate = dateFormat.format(today.plus(Period.days(offset)).toDate());

到目前为止,我还检查了将 350 天左右添加到这 11 天的时间段中,它也给出了错误的日期。 我知道我可以使用 Joda-time 格式化程序,但我仍然找不到问题所在,任何帮助都会很好:)

(对于遇到过此问题的人):

DateTimeFormatter fmt = DateTimeFormat.forPattern(SimpleFormat);

问题不在于日期或日期时间,而在于格式化程序。

YYYY 表示 ISO 周年。但是,一年中最后一周的 ISO Week 年 is the next year.

yyyy表示日历年,这就是你真正想要的。