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

查看:125
本文介绍了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年的最后两天是在周末的第一周您通常只能使用周年与一周说明符( 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天全站免登陆