Java 日期年份计算按年份关闭两天 [英] Java Date year calculation is off by year for two days

查看:31
本文介绍了Java 日期年份计算按年份关闭两天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你能想象,这会在我的软件中导致一个 Y2K 风格的错误.奇怪的是,逐年计算只在一年中出现两天,我不太确定如何排除故障.

This caused a Y2K-style bug in my software if you can imagine. Strange thing is the off-by-one year calculation only occurs for two days in the year, which I'm less sure how to troubleshoot.

输出:

03-Jan-2013
02-Jan-2013
01-Jan-2013
31-Dec-2013 ** strange
30-Dec-2013 ** strange
29-Dec-2012
28-Dec-2012
27-Dec-2012
26-Dec-2012
25-Dec-2012

我不确定 Java 日期实用程序的哪一部分会导致此类错误.

I am not sure which part of the Java date utilities could cause such an error.

代码(由于测试很小,我包含了一个完整的工作程序):

The code (since the test is so small I included a complete working program):

import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;

public class DateT {

        private static String getFormattedBackscanStartTime(int days) {

                SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-YYYY");
                Calendar workingDate = Calendar.getInstance();
                workingDate.add(Calendar.DATE, -1 * days);

                String formattedStartTime = dateFormat.format(workingDate.getTime());
                return formattedStartTime;
        }

        public static void main(String args[]) {

                for(int i = 35; i < 45; i++) {
                        System.out.println(getFormattedBackscanStartTime(i));
                }
        }
}

推荐答案

这是问题所在:

"dd-MMM-YYYY"

YYYY 是周年,而不是日历年.你想要 yyyy 代替.

YYYY is the week-year, not the calendar year. You want yyyy instead.

2012 日历年的最后两天是 2013 年周的第一周.您通常只应将周年与一年中的周"说明符 (w) 结合使用.

The last two days of calendar year 2012 were in the first week of week-year 2013. You should normally only use the week year in conjunction with the "week of year" specifier (w).

这篇关于Java 日期年份计算按年份关闭两天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆