Java 日期年计算按年关闭两天

Java Date year calculation is off by year for two days(Java 日期年计算按年关闭两天)

本文介绍了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 日期年计算按年关闭两天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java 日期年计算按年关闭两天

基础教程推荐