这是写这个的好方法,还是我可以使用的那种不那么臃肿的形式?
import java.util.Calendar;
public class Day {
public static void main(String[] args){
Calendar cal = Calendar.getInstance();
System.out.println("Todays date is : " + cal.getTime());
//increment by one from current date
int OneIncrementalDay = 1;
cal.getTime();
cal.add(Calendar.DATE,
OneIncrementalDay);
System.out.println("Tomorrows date is : " + cal.getTime());
//deduction by one from current date
int OneDayDeducted = -1;
cal.getTime();
cal.add(Calendar.DATE,
OneDayDeducted);
System.out.println("Yesterdays date was : " + cal.getTime());
cal.getTime();
//increment of 15 from current date
int FifteenDaysIncremental = 15;
cal.getTime();
cal.add(Calendar.DATE,
FifteenDaysIncremental);
System.out.println("15 days from the current"
+ " date is : " + cal.getTime());
}
}
答案 0 :(得分:0)
是的,如果您使用的是Java 8,则可以使用新的java.time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
...
//or whatever format you want to use
DateTimeFormatter fmt = DateTimeFormatter.ISO_LOCAL_DATE;
//java.time.LocalDate
LocalDate today = LocalDate.now();
System.out.println("Todays date is : " + today.format(fmt));
//increment by one from current date
System.out.println("Tomorrows date is : " + today.plusDays(1).format(fmt));
System.out.println("Yesterdays date was : " + today.minusDays(1).format(fmt));
System.out.println("15 days from the current date is " + today.plusDays(15).format(fmt));
还有添加/减去月份等的方法
答案 1 :(得分:0)
你所拥有的东西对可读性有好处,但如果你真的想缩小它,你可以做一件事。由于除了值之外,三个块中的每个块基本相同,因此将所有值放在长度为3的数组中,然后使用for循环来适当地更改值,例如:
int[] increments = {1, -1, 15};
String[] text = {"Tomorrows date is : ",
"Yesterdays date was : ",
"15 days from the current date is : "};
for (int i = 0; i < increments.length; i++)
{
cal.getTime();
cal.add(Calendar.DATE, increments[i]);
System.out.println(text[i] + cal.getTime());
}
答案 2 :(得分:0)
如果我是那个程序员我会这样做
import java.util.Calendar;
public class Day {
Calendar cal = Calendar.getInstance();
public Calendar inCrementNumberofDays(Integer day){
cal.getTime();
cal.add(Calendar.DATE,
day);
return cal;
}
public Calendar decrementNumberofDays(Integer day){
day = day * -1;
cal.getTime();
cal.add(Calendar.DATE,
day);
return cal;
}
public static void main(String[] args){
System.out.println("Todays date is : " + cal.getTime());
//increment by one from current date
cal = inCrementNumberofDays(1);
System.out.println("Tomorrows date is : " + cal.getTime());
//deduction by one from current date
cal = decrementNumberofDays(1);
System.out.println("Yesterdays date was : " + cal.getTime());
//increment of 15 from current date
cal = inCrementNumberofDays(15);
System.out.println("15 days from the current"
+ " date is : " + cal.getTime());
}
}