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

2020-03-07 08:49发布

问题:

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

回答1:

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



回答2:

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


回答3:

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

}


回答4:

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



回答5:

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


回答6:

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.


回答7:

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



    }

}


回答8:

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


标签: java class date