如何用Java获得过去或未来的日期?

22-09-18 banq

使用日历对象使用 add() 方法转到未来日期或过去日期:

import java.util.Calendar;

public class CalendarAddExample1 {

    public static void main(String[] args) {
        // current calendar date
        Calendar calendar = Calendar.getInstance();

        System.out.println("Current time - " + calendar.getTime());

        // Adding 10 days to get the future date
        calendar.add(Calendar.DATE, 10);
        System.out.println("10 days future time - " + calendar.getTime());

        // 10 days old date to get the past date
        calendar.add(Calendar.DATE, -10);
        System.out.println("10 days past time - " + calendar.getTime());

        // future 10 years
        calendar.add(Calendar.YEAR, 10);
        System.out.println("10 years future time - " + calendar.getTime());

        // past 10 years
        calendar.add(Calendar.YEAR, -10);
        System.out.println("10 years back time - " + calendar.getTime());

        // future 10 months
        calendar.add(Calendar.MONTH, 10);
        System.out.println("10 months future time - " + calendar.getTime());

        // past 10 months
        calendar.add(Calendar.MONTH, -10);
        System.out.println("10 months back time - " + calendar.getTime());

    }

}


使用 Calendar.HOUR 和 Calendar.MINUTE :

import java.util.Calendar;

public class CalendarAddExample2 {

    public static void main(String[] args) {
        // current calendar date
        Calendar calendar = Calendar.getInstance();

        System.out.println("Current time - " + calendar.getTime());

        calendar.add(Calendar.HOUR, 1);
        System.out.println("adding one hour" + calendar.getTime());

        calendar.add(Calendar.HOUR, -1);
        System.out.println("one hour back time - " + calendar.getTime());

        // future 10 minutes
        calendar.add(Calendar.MINUTE, 10);
        System.out.println("10 minutes future time - " + calendar.getTime());

        // past 10 minutes
        calendar.add(Calendar.MINUTE, -10);
        System.out.println("10 minutes back time - " + calendar.getTime());

    }

}