gpt4 book ai didi

java - 使用 while 循环向日期添加天数

转载 作者:行者123 更新时间:2023-12-02 01:03:10 24 4
gpt4 key购买 nike

我正在编写一个程序,将天数添加到当前日期和已经给定的日期。我正在努力让我的代码正确添加天数。我认为我正确地执行了几天的 while 循环,但我还需要执行几个月的 while 循环。我将如何编写这几个月的 while 循环?我的看法是,我需要不断地添加一个月并减去适当的天数,直到剩下的天数少于 30(或 31、或 29)天,并且不能简单地添加一个月。是对的吗?到目前为止我的代码正确吗?

这是我到目前为止的代码:

   class Dates {

public String[] MONTH_NAMES = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
public List<Integer> ODD_MONTHS = Arrays.asList(1, 3, 5, 7, 8, 10, 12);
public int year;
public int month;
public int day;

public Dates(int y, int m, int d) {
day = d;
month = m;
year = y;
}

public void addDays(int days) {
while (days > 365) {
{
if (isLeapYear()) {
days -= 1;
}
days -= 365;
year += 1;
if (isLeapYear() && month == 2 && day > 28 ) {
day -= 29;
month++;
} else if (ODD_MONTHS.contains(month) && day > 30) {
day -= 31;
month++;
} else if (day > 29) {
day -= 30;
month++;
}
}
}
}

public void subtractDays(int days) {
year -= days / 365;
days %= 365;
month -= days / 30;
days %= 30;
day -= days;
if (isLeapYear() && month == 2 && day > 28) {
day += 28;
month--;
} else if (ODD_MONTHS.contains(month) && day > 31) {
day += 31;
month--;
} else if (day > 30) {
day += 30;
month--;
}
}

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

public String getMonthName() {
return MONTH_NAMES[month];
}

public int getMonth() {
return month;
}

public int getYear() {
return year;
}

public int getDayOfMonth() {
return day;
}

public void printShortDate() {
System.out.println(String.format("%d/%d/%d", month, day, year));
}

public void printLongDate() {
System.out.println(String.format("%s %d, %d", getMonthName(), day, year));
}
}


class GregorianDate extends Dates {

public GregorianDate() {
super(1970, 1, 1);
long milliSeconds = System.currentTimeMillis() + java.util.TimeZone.getDefault().getRawOffset();
int days = (int) milliSeconds / 1000 / 60 / 60 / 24;
addDays(days);
}

public GregorianDate(int year, int month, int day) {
super(year, month, day);
}
}

class JulianDate extends Dates {

public JulianDate() {
super(1, 1, 1);
addDays(719164);
long milliSeconds = System.currentTimeMillis() + java.util.TimeZone.getDefault().getRawOffset();
int days = (int) milliSeconds / 1000 / 60 / 60 / 24;
addDays(days);
}

public JulianDate(int year, int month, int day) {
super(year, month, day);
}
}

最佳答案

尝试使用java 8时间。如果不可能,请使用 Joda Time。

两者都能够添加迄今为止的天数,例如:

DateTime dateTime = new DateTime(date);
dateTime = dateTime.plusDays(1);

你不应该从头开始写它。只需使用以上其中之一即可。

关于java - 使用 while 循环向日期添加天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60401202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com