java - 如何在不从java API导入日期/日历的情况下将n天添加到java中的日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23534528/
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-08-13 23:41:12  来源:igfitidea点击:

How to add n days to a Date in java without importing Date/Calendar from java API?

javaclassdate

提问by Messit?zil

How do I add n days to a date in Java Creating my own java class?

如何在 Java 创建我自己的 Java 类中为日期添加 n 天?

For example, my date is (dd/mm/yyyy) = 26/02/2014

例如,我的日期是 (dd/mm/yyyy) = 26/02/2014

Adding 3 days, the output should be 01/03/2014.

加上 3 天,输出应该是01/03/2014.

Without importing Calendar or Date from JAVA API

无需从 JAVA API 导入日历或日期

Thank you in Advance. Any Sample code or Pseudo Code or idea will be highly apprecited

先感谢您。任何示例代码或伪代码或想法都将受到高度赞赏

回答by Alex

Convert the date to days. For example how many days passed from 01/01/1900then add 3 days and convert it back.

将日期转换为天。例如,01/01/1900从那时起过去了多少天,然后加上 3 天并将其转换回来。

回答by Evgeniy Dorofeev

try this

尝试这个

class Date {
    static int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int m;
    int d;
    int y;

    Date(String date) {
        // parse and get int fields
    }

    Date(int d, int m, int y) {
        this.d = d;
        this.m = m;
        this.y = y;
    }

    int maxDays() {
        int md = daysInMonth[m - 1];
        // correction for Feb
        return md;
    }

    Date addDays(int n) {
        int d = this.d += n;
        int m = this.m;
        int y = this.y;
        while (d > maxDays()) {
            d = d - maxDays();
            m++;
            if (m > 12) {
                y++;
                m = 1;
            }
        }
        return new Date(d, m, y);
    }
}

note that code may need fixing

请注意,代码可能需要修复

回答by Niru

This was one of my interview question, I had return the below code on paper may be my bad luck :-( I didn't get selected in that round, may be interviewer was not able to understand :-) :-). I just searched to see is there any better way of doing it but I didn't, so I wrote same code what I had written on paper but its working like charm. Hope fully my confidence remains same :-) :-)

这是我的面试问题之一,我在纸上返回了以下代码可能是我运气不好:-(我在那轮没有被选中,可能是面试官无法理解:-):-)。我只是想看看有没有更好的方法来做,但我没有,所以我写了与我在纸上写的相同的代码,但它的工作方式很有魅力。希望我的信心保持不变:-) :-)

Hope this help you or some body.

希望这对您或某些机构有所帮助。

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class MyDate
{
    private static final Map<Integer, Integer>  daysInMonth;

    static
    {
        daysInMonth = new HashMap<Integer, Integer>();
        daysInMonth.put(1, 31);
        daysInMonth.put(2, 28);
        daysInMonth.put(3, 31);
        daysInMonth.put(4, 30);
        daysInMonth.put(5, 31);
        daysInMonth.put(6, 30);
        daysInMonth.put(7, 31);
        daysInMonth.put(8, 31);
        daysInMonth.put(9, 30);
        daysInMonth.put(10, 31);
        daysInMonth.put(11, 30);
        daysInMonth.put(12, 31);
    }

    private int                                 day;
    private int                                 month;
    private int                                 year;
    private int                                 amount;

    public MyDate(int day, int month, int year)
    {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public MyDate addOrSubDays(int amount)
    {
        this.amount = amount;
        return addOrSubDays(this.day + this.amount, this.month, this.year);
    }

    public static void main(String[] args)
    {
        int amount = 650;

        MyDate myDate = new MyDate(21, 5, 2016);
        MyDate addOrSubDays = myDate.addOrSubDays(amount);

        System.out.println(addOrSubDays.getDay() + "-" + addOrSubDays.getMonth() + "-" + addOrSubDays.getYear());

        // Testing
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, amount);
        System.out.println(cal.getTime());
    }

    private MyDate addOrSubDays(int days, int month, int year)
    {
        if (days > 0 && days <= getNoOfDaysInMonth(month, year))
        {
            return new MyDate(days, month, year);
        }
        else if (days <= 0)
        {
            month = month - 1;
            if (month == 0)
            {
                month = 12;
                year = year - 1;
            }
            days = getNoOfDaysInMonth(month, year) + days;
        }
        else
        {
            month = month + 1;
            if (month > 12)
            {
                month = 1;
                year = year + 1;
            }
            days = days - getNoOfDaysInMonth(month, year);
        }
        return addOrSubDays(days, month, year);
    }

    private int getNoOfDaysInMonth(int month, int year)
    {
        if (month == 2 && checkIsLeepYear(year))
        {
            return daysInMonth.get(month) + 1;
        }
        return daysInMonth.get(month);
    }

    private boolean checkIsLeepYear(int year)
    {
        if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
        {
            return true;
        }
        return false;
    }

    public int getDay()
    {
        return day;
    }

    public int getMonth()
    {
        return month;
    }

    public int getYear()
    {
        return year;
    }

    public int getAmount()
    {
        return amount;
    }
}

回答by Gilbert Le Blanc

Since everyone is putting their Date class here, I'll post mine.

由于每个人都将他们的 Date 课程放在这里,我将发布我的课程。

Here are test results.

以下是测试结果。

Jun 12, 2014 + 10 days -> Jun 22, 2014
Jun 12, 2014 + 20 days -> Jul 2, 2014
Dec 15, 2014 + 20 days -> Jan 4, 2015
Dec 15, 1955 + 30 days -> Jan 14, 1956
Dec 15, 1955 - 30 days -> Nov 15, 1955
Dec 15, 1955 + 16 days -> Dec 31, 1955
Dec 15, 1955 + 17 days -> Jan 1, 1956
Dec 15, 1955 + 80 days -> Mar 4, 1956
Dec 15, 1956 + 80 days -> Mar 5, 1957
Mar 5, 1957 - 80 days -> Dec 15, 1956
Mar 5, 1956 - 80 days -> Dec 16, 1955

And here's the code. I formatted my dates in a month, day, year format. You can change the getFormattedOutput method to be in a day, month, year format.

这是代码。我以月、日、年格式格式化我的日期。您可以将 getFormattedOutput 方法更改为日、月、年格式。

package com.ggl.testing;

import java.security.InvalidParameterException;

public class Date {

    private static final boolean DEBUG = false;

    private static final int BASE_MONTH = 1;
    private static final int BASE_YEAR = 1700;

    private int days;

    public Date(int month, int day, int year) {
        setDate(month, day, year);
    }

    public void setDate(int month, int day, int year) {
        if ((month >= 1) && (month <= 12)) {
        } else {
            String s = "Month not between 1 and 12";
            throw new InvalidParameterException(s);
        }

        if (year >= BASE_YEAR) {
            int temp = calculateMonthDays(month, year);
            if ((day >= 1) && (day <= temp)) {
            } else {
                String s = "Day not between 1 and " + temp;
                throw new InvalidParameterException(s);
            }

            int days = calculateYearDays(year);
            if (DEBUG) {
                System.out.println(days);
                System.out.println(temp);
            }

            days += temp;
            this.days = days + day;
            if (DEBUG) {
                System.out.println(day);
                System.out.println(this.days);
            }
        } else {
            String s = "Year before " + BASE_YEAR;
            throw new InvalidParameterException(s);
        }
    }

    public int[] getDate() {
        int days = this.days;
        if (DEBUG)
            System.out.println(days);

        int year = BASE_YEAR;
        int decrement = daysInYear(year);
        while (days > decrement) {
            days -= decrement;
            decrement = daysInYear(++year);
        }
        if (DEBUG)
            System.out.println(days);

        int month = BASE_MONTH;
        decrement = daysInMonth(month, year);
        while (days > decrement) {
            days -= decrement;
            decrement = daysInMonth(++month, year);
        }
        if (DEBUG)
            System.out.println(days);

        int day = days;

        int[] result = new int[3];
        result[0] = month;
        result[1] = day;
        result[2] = year;

        return result;
    }

    public String getFormattedDate() {
        String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
                "Aug", "Sep", "Oct", "Nov", "Dec" };
        int[] fields = getDate();
        return String.format("%s %d, %d", months[fields[0] - 1], fields[1],
                fields[2]);
    }

    public void addDays(int increment) {
        this.days += increment;
    }

    private int calculateMonthDays(int month, int year) {
        int days = 0;

        for (int i = BASE_MONTH; i < month; i++) {
            days += daysInMonth(i, year);
        }

        return days;
    }

    private int calculateYearDays(int year) {
        int days = 0;

        for (int i = BASE_YEAR; i < year; i++) {
            days += daysInYear(i);
        }

        return days;
    }

    private int daysInMonth(int month, int year) {
        int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

        if (month == 2) {
            if (daysInYear(year) > 365) {
                return days[month - 1] + 1;
            }
        }

        return days[month - 1];
    }

    private int daysInYear(int year) {
        int days = 365;

        if ((year % 4) == 0) {
            if ((year % 100) == 0) {
                if ((year % 400) == 0) {
                    days++;
                }
            } else {
                days++;
            }
        }

        return days;
    }

    public static void main(String[] args) {
        Date date = new Date(6, 12, 2014);
        displayResult(date, 10);

        date = new Date(6, 12, 2014);
        displayResult(date, 20);

        date = new Date(12, 15, 2014);
        displayResult(date, 20);

        date = new Date(12, 15, 1955);
        displayResult(date, 30);

        date = new Date(12, 15, 1955);
        displayResult(date, -30);

        date = new Date(12, 15, 1955);
        displayResult(date, 16);

        date = new Date(12, 15, 1955);
        displayResult(date, 17);

        date = new Date(12, 15, 1955);
        displayResult(date, 80);

        date = new Date(12, 15, 1956);
        displayResult(date, 80);

        date = new Date(3, 5, 1957);
        displayResult(date, -80);

        date = new Date(3, 5, 1956);
        displayResult(date, -80);
    }

    private static void displayResult(Date date, int increment) {
        String sign = "";
        int display = 0;

        if (increment > 0) {
            sign = " + ";
            display = increment;
        } else {
            sign = " - ";
            display = -increment;
        }

        System.out
                .print(date.getFormattedDate() + sign + display + " days -> ");
        date.addDays(increment);
        System.out.println(date.getFormattedDate());
    }

}

回答by Mithil Aggarwal

class DateCalculator{
    private int[] normalYear = {31,28,31,30,31,30,31,31,30,31,30,31};
    private int[] leapYear = {31,29,31,30,31,30,31,31,30,31,30,31};

    public String calculateDate(String date, int numberOfDays){
        String[] date_parts = date.split("/");
        int year = Integer.parseInt(date_parts[2]);
        int month = Integer.parseInt(date_parts[1]);
        int day = Integer.parseInt(date_parts[0]);
        int days = numberOfDays;
        int[] refYear = getRefYear(year);
        while(true){
            int diff = days - (refYear[month - 1] - day);
            if(diff > 0 ){
                days = diff;
                month++;
                day = 0;
                if(month <= 12){
                    continue;
                }
            }else{
                day = day + days;
                break;
            }
            year++;
            month = 1;
            refYear = getRefYear(year);
        }

        StringBuilder finalDate = new StringBuilder();
        finalDate.append(day);
        finalDate.append("/");
        finalDate.append(month);
        finalDate.append("/");
        finalDate.append(year);

        return finalDate.toString();

    }

    private int[] getRefYear(int year){

        return isLeapYear(year)? leapYear : normalYear;
    }

    private boolean isLeapYear(int year){
        if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)  ){
            return true;
        }
        return false;
    }
}

回答by Kiran Dulam

Question: increase or update given date by certain days, without using calendar or date class?

问题:在不使用日历或日期类的情况下将给定日期增加或更新特定天数?

Answer: I verified first ex and that seems like good a reference for storing values in maps (as days for months are fixed).

答:我首先验证了前例,这似乎是在地图中存储值的好参考(因为几个月的天数是固定的)。

My solution is below and it is working correctly, when I tested.

我的解决方案如下,当我测试时它工作正常。

Solution code:

解决方案代码:

import java.util.*;
public class IncreaseDate {

    private static final Map<Integer, Integer> date;

    static {
        date= new HashMap<Integer,Integer>();
        date.put(1,31);
        date.put(2,28);
        date.put(3,31);
        date.put(4,30);
        date.put(5,31);
        date.put(6,30);
        date.put(7,31);
        date.put(8,31);
        date.put(9,30);
        date.put(10,31);
        date.put(11,30);
        date.put(12,31);
    }

    public static void main(String args[])  {
        IncreaseDate id= new IncreaseDate();
        System.out.println("2/5/2018 "+"+"+60+" : ");
        id.updateDate(2,5,2018,60);
    }

    public void updateDate(int m,int d, int y, int days) {
        int temp=date.get(m);
        // for finding leap year
        if(m==2 && (y%4==0 && y%100!=0 && y%400!=0)) {
            temp= date.get(m)+1;
        }
        if(d+days>temp) {
            if(m<=11) {
                updateDate(m+1,d,y,days-temp);
            }
            else {
                updateDate(1,d,y+1,days-temp);
            }
        }
        else {
            System.out.println("Upadate Date: "+m+"/"+(d+days)+"/"+y);
        }
    }
}

Points to remember:

要记住的要点:

  • We are updating months and years and decreasing days until it becomes less than that month days.
  • Calendar class is abstract class, so we cant create object directly. But we can create using getInstance() factory method.
  • 我们正在更新月份和年份并减少天数,直到它变得少于该月的天数。
  • Calendar 类是抽象类,所以我们不能直接创建对象。但是我们可以使用 getInstance() 工厂方法创建。

回答by neelmani baghel

package StringProgram;

public class AddingDaystoDate {

    public static String addDays(String date, int n)
    {
        int[] daysInNormalYear={31,28,31,30,31,30,31,31,30,31,30,31};
        int[] daysInLeapYear={31,29,31,30,31,30,31,31,30,31,30,31};
        String[] sArray=date.split("/");
        int dd=Integer.valueOf(sArray[0]);
        int mm=Integer.valueOf(sArray[1]);
        int yy=Integer.valueOf(sArray[2]);
        String updatedDate="";

        if(calculateLeapYear(yy)==true)
        {
            int maxDayinMonth=daysInLeapYear[mm-1];
            dd=dd+n;
            if(dd>maxDayinMonth)
            {
                dd=dd-maxDayinMonth;
                mm++;
                if(mm>12)
                {
                    yy++;
                    mm=1;
                }

            }

            updatedDate=new String(""+dd+"/"+mm+"/"+yy);
        }
        else
        {
            int maxDayinMonth=daysInNormalYear[mm-1];
            dd=dd+n;
            if(dd>maxDayinMonth)
            {
                dd=dd-maxDayinMonth;
                mm++;
                if(mm>12)
                {
                    yy++;
                    mm=1;
                }

            }

            updatedDate=new String(""+dd+"/"+mm+"/"+yy);
        }
        return updatedDate;
    }
    public static boolean calculateLeapYear(int year)
    {
        if(year%4==0)
        {
            if(year%100==0)
            {
                if(year%400==0)
                {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    public static void main(String[] args) {
        String date="27/12/2014";

        String s=addDays(date,5);

        System.out.print(s);



    }

}

回答by sam

simple code for add or sub using method

添加或子使用方法的简单代码

    public Date1(int d, int m, int y) {

        this.day = d;
        this.month = m;
        this.year = y;
    }



  public void addDay() {
    month--;
    Calendar m = Calendar.getInstance();
    m.set(year, month, day);
    m.add(day, 5); // if you want add or sub month or year it depend on days 

    java.sql.Date d = new java.sql.Date(m.getTimeInMillis());
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println(" date is  " + df.format(d));