How to add n days to a Date in java without import

2020-03-07 08:07发布

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

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

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

Without importing Calendar or Date from JAVA API

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

标签: java class date
8条回答
Melony?
2楼-- · 2020-03-07 08:47

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

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.

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());
    }

}
查看更多
三岁会撩人
3楼-- · 2020-03-07 08:55

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

查看更多
欢心
4楼-- · 2020-03-07 08:57
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);



    }

}
查看更多
做自己的国王
5楼-- · 2020-03-07 08:59

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));
查看更多
Fickle 薄情
6楼-- · 2020-03-07 09:03

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

查看更多
走好不送
7楼-- · 2020-03-07 09:07

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;
    }
}
查看更多
登录 后发表回答