2

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

 2 years ago
source link: https://www.jdon.com/62493
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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


使用日历对象使用 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());

    }

}

 


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK