如何解决将天数转换为日期的方法
用户要求输入1到365之间的数字。该数字表示一年中的天数。显示相应的日期。
我陷入了方法CalculationDateWithDayNumber
一个例子:数字105应该转换为4月15日。我的结果是2月-31日。 哪里出问题了?
public class DateOperations {
private final static String[] MONTHS = {"January","February","March","April","May","June","July","August","September","October","November","December" };
private static final int[] NUMBERDAYS = {31,28,31,30,31};
public static String calculationDateWithDayNumber(int day)
{
int month = 0;
for (int i=0; day>=NUMBERDAYS[i] ;i++)
{day=-NUMBERDAYS[i];
++ month;}
String nameMonth = MONTHS[month];
String datum = String.format("%d%s",day,nameMonth);
return datum;
}
}
解决方法
您可以使用ofYearDay
通过java.time API轻松完成此操作。由于您说的数字可以是1到365,因此您可能假设非assuming年,因此您可以将任何非le年作为第一个参数:
Line Input
,
我想你正在练习。 需要两个修复程序,请参见下面的代码注释
day=-NUMBERDAYS[i]
表示您在NUMBERDAYS[i]
中分配了(-1 * day
)的值。但是我认为您应该像NUMBERDAYS[i]
那样从day
减去day - NUMBERDAYS[i]
,然后像day
那样在day = day - NUMBERDAYS[i]
中分配值,或者使用day -= NUMBERDAYS[i]
这样的简写运算符
public static String calculationDateWithDayNumber(int day) {
int month = 0;
for (int i = 0; day > NUMBERDAYS[i]; i++) { // Fix here,remove equals since day can be last day of month
day = day - NUMBERDAYS[i]; // Fix here,minus the NUMBERDAYS[i] from day
++month;
}
String nameMonth = MONTHS[month];
String datum = String.format("%d %s",day,nameMonth);
return datum;
}
输出:15 April
自register
起,无需进行任何自定义计算即可完成此任务(这一点都不微不足道)。
基本上,您可以只输入今天的日期,并调整保留年份的日期。看这个例子:
<Controller
control={control}
name="test"
render={({ onChange,onBlur,value }) => (
<Checkbox
onBlur={onBlur}
onChange={e => onChange(e.target.checked)}
checked={value}
/>
)}
/>
<Controller render={props => <Input {...props} />} />
在java.time
之类的方法中使用它
public static String getDateFromDayOfYear(int dayOfYear) {
// take "today" (basically just to have the current year
LocalDate localDate = LocalDate.now()
// and adjust the day of year using the argument
.withDayOfYear(dayOfYear);
// then return a String representation of that date in a desired format (GER/DE here)
return localDate.format(DateTimeFormatter.ofPattern("dd.MM.uuuu"));
}
将输出
main
这显然不是您想要的输出,因为您的任务没有考虑leap年
(由于2020年2月29日而有366天的时间)。
我认为您需要以下代码段:
public static void main(String[] args) {
int dayOfYear = 60;
int year = 2019;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.DAY_OF_YEAR,dayOfYear);
System.out.println("Day " + dayOfYear + " of the current year = " + calendar.getTime());
}
您需要设置年份,以采用the年