如何在不从Java API导入日期/日历的情况下向Java中的日期添加n天? [英] How to add n days to a Date in java without importing Date/Calendar from java API?

查看:66
本文介绍了如何在不从Java API导入日期/日历的情况下向Java中的日期添加n天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中为日期添加n天呢?

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

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

相加3天,输出应为 01/03 / 2014

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

Without importing Calendar or Date from JAVA API

谢谢提前。

推荐答案

尝试此

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

这篇关于如何在不从Java API导入日期/日历的情况下向Java中的日期添加n天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆