Java 各種時間上的操作範例

分享一些在專案中用到JAVA與日期相關的操作,包括:

  • 取得目前的年、月、日
  • 判斷兩個日期的大小
  • 計算兩個日期的差距
  • 取得昨天的日期
  • 取得上個月的開始與結束日
package CDIT.stanley;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Calendar;

public class dateOperation {
	
	public static int differentDays(Date date1,Date date2){
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2){
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++){
                if(i%4==0 && i%100!=0 || i%400==0){
                    timeDistance += 366;
                }
                else{
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        }
        else{
            return day2-day1;
        }
    }
	
	public static Date getFirstMonthDay(Calendar calendar) {
		calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DATE));
		return calendar.getTime();
	}

	public static Date getLastMonthDay(Calendar calendar) {
		calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
		return calendar.getTime();
	}
	
    public static void main(String[] args) throws ParseException {
    	
    	//取得目前的年、月、日
		Calendar calendar = Calendar.getInstance();	
		System.out.println("今天是" + calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日");
		System.out.println("==================================================");
    	//輸出:今天是2017年8月24日
		
		//判斷兩個日期的大小
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN);
    	Date date1 = sdf.parse("2017-08-23");
    	Date date2 = sdf.parse("2016-09-22");
		System.out.println("Date1 < Date2 : " + date1.before(date2));
		System.out.println("Date1 > Date2 : " + date1.after(date2));
		System.out.println("==================================================");
		//輸出:Date1 < Date2 : false、Date1 > Date2 : true
		
		//計算兩個日期的差距
		System.out.println("Date1 & Date2 差距 : " + differentDays(date1 , date2) + "天");
		System.out.println("==================================================");
		//輸出:Date1 & Date2 差距 : 31天
		
		//取得昨天的日期
		calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		String  yestedayDate = sdf.format(calendar.getTime());
		System.out.println("昨天是" + yestedayDate);
		System.out.println("==================================================");
		//輸出:昨天是2017-08-23
		
		//取得上個月的開始與結束日
		calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH,-1);
		String monthDayFirst = sdf.format(getFirstMonthDay(calendar));
		String monthDayLast = sdf.format(getLastMonthDay(calendar));
		System.out.println("上個月的第一天是" + monthDayFirst);
		System.out.println("上個月的最後一天是" + monthDayLast);
		System.out.println("==================================================");
		//輸出:上個月的第一天是2017-07-01、上個月的最後一天是2017-07-31
    }
}

You may also like...

27,956 Responses

  1. Briantrozy表示:

    cost of clomid without insurance: ClmHealthPharm – how to get cheap clomid without insurance

  2. BrandonJag表示:

    where to get cheap clomid prices: ClmHealthPharm – cost of clomid

  3. JustinTam表示:

    can i buy zithromax online: how to buy zithromax online – generic zithromax medicine

  4. Briantrozy表示:

    amoxicillin 500 mg capsule: amoxicillin order online – cost of amoxicillin prescription

  5. Fantastic beat ! I would like to apprentice whilst you amend your web site, how could i subscribe for a weblog site? The account helped me a appropriate deal. I had been a little bit familiar of this your broadcast provided bright clear concept

  6. Roberttic表示:

    http://doxhealthpharm.com/# doxycycline 225 mg

  7. JustinTam表示:

    get generic clomid no prescription: ClmHealthPharm – can i get clomid no prescription

  8. Roberttic表示:

    http://zithropharm.com/# where can i buy zithromax uk

  9. BrandonJag表示:

    cost of doxycycline 50 mg: Dox Health Pharm – doxycycline capsules india

  10. JustinTam表示:

    zithromax 600 mg tablets: where to buy zithromax in canada – zithromax 250 mg tablet price

  11. BrandonJag表示:

    zithromax for sale usa: Zithro Pharm – how to buy zithromax online

  12. JustinTam表示:

    how to get clomid: how to get generic clomid for sale – generic clomid tablets

  13. The 1xCasino promo code 2025: “1XBUM” welcome bonus is 100% up to €2205 and 75 Free Spins No Deposit Bonus. You need to register, confirm your email and enter bonus code. Register a new account with 1xCasino using the code and enjoy 100 free spins at registration.

    promo code for 1xcasino pakistan

  14. Briantrozy表示:

    get cheap clomid for sale: ClmHealthPharm – can you buy cheap clomid without prescription

  15. JustinTam表示:

    zithromax z-pak: zithromax generic cost – generic zithromax azithromycin

  16. This model allows for a more holistic and integrated approach to mental health, ensuring that patients receive the necessary support and treatment from a multidisciplinary team.

  17. Hi, i think that i saw you visited my blog thus i came to ?return the favor?.I’m trying to find things to enhance my site!I suppose its ok to use a few of your ideas!!

  18. Briantrozy表示:

    cost of clomid without dr prescription: cost clomid pills – can i order cheap clomid

  19. And in the case of the Gymnetis flower beetle, this has acquired to be one of the best interpretations I’ve seen for the velvety black colour transitioning into yellow on the beetle’s elytra.

  20. Reckchelkokiz表示:

    The 1xCasino promo code 2025: “1XBUM” welcome bonus is 100% up to €2205 and 75 Free Spins No Deposit Bonus. You need to register, confirm your email and enter bonus code. Register a new account with 1xCasino using the code and enjoy 100 free spins at registration.

    1xcasino promo code for free bet

  21. Roberttic表示:

    http://doxhealthpharm.com/# doxycycline 200 mg pill

  22. BrandonJag表示:

    doxycycline 20mg canada: doxycycline 50 mg – how can i get doxycycline

  23. Roberttic表示:

    http://clmhealthpharm.com/# order generic clomid pill

  24. Briantrozy表示:

    doxycycline cost in mexico: doxycycline 10mg tablets – doxycycline prescription australia

  25. That is where a professional marriage ceremony planner in Delhi, like V3 Occasions & Weddings, is available in, guaranteeing each aspect of your huge day is flawlessly managed.

  26. Hello! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  27. VirgilBlawl表示:

    can you buy zithromax over the counter in australia ZithroPharm generic zithromax india

  28. Briantrozy表示:

    zithromax cost: Zithro Pharm – zithromax buy online

  29. BrandonJag表示:

    amoxicillin 1000 mg capsule: amoxicillin online canada – amoxicillin capsules 250mg

  30. JustinTam表示:

    purchase amoxicillin online without prescription: Amo Health Pharm – ampicillin amoxicillin

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。