How can change my code so results are based on user input of years and days?
I have written the code below to calculate the date of "two years ago" based off the "today's date", as well as the date of "5 days ahead".
I want to make a dynamic version of the code, follow开发者_运维技巧ing the same comparison principle. For example, I want the user to insert the numbers of years and days and compare it to today's date.
Code:
public class Calendar1{
private static void doCalendarTime() {
System.out.print("*************************************************");
Date now = Calendar.getInstance().getTime();
System.out.print(" \n Calendar.getInstance().getTime() : " + now);
System.out.println();
}
private static void doSimpleDateFormat() {
System.out.print("*************************************************");
System.out.print("\n\nSIMPLE DATE FORMAT\n");
System.out.print("*************************************************");
// Get today's date
Calendar now = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.print(" \n It is now : " + formatter.format(now.getTime()));
System.out.println();
}
private static void doAdd() {
System.out.println("ADD / SUBTRACT CALENDAR / DATEs");
System.out.println("=================================================================");
// Get today's date
Calendar now = Calendar.getInstance();
Calendar working;
SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
working = (Calendar) now.clone();
working.add(Calendar.DAY_OF_YEAR, - (365 * 2));
System.out.println (" Two years ago it was: " + formatter.format(working.getTime()));
working = (Calendar) now.clone();
working.add(Calendar.DAY_OF_YEAR, + 5);
System.out.println(" In five days it will be: " + formatter.format(working.getTime()));
System.out.println();
}
public static void main(String[] args) {
System.out.println();
doCalendarTime();
doSimpleDateFormat();
doAdd();
}
}
Java's standard date-time APIs are not very good for operations on dates. If you want to do real calculations on dates, I suggest a library like Joda-Time, which has much better functionality for such cases.
Here is the a Joda-Time code following the same example used on the question:
DateTime now = new DateTime();
DateTime twoYearsAgo = now.minusYears(2);
DateTime fiveDaysFromNow = now.plusDays(5);
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("E yyyy.MM.dd 'at' hh:mm:ss a zzz")
.toFormatter();
System.out.println(formatter.print(twoYearsAgo));
System.out.println(formatter.print(fiveDaysFromNow));
This assumes you want to work with the system's default time-zone (meridian). If that is not the case, there is a constructor's argument to set the time-zone that will be used.
精彩评论