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,704 Responses

  1. NorbertKep表示:

    Pharmacie en ligne livraison Europe: Pharmacies en ligne certifiees – vente de mГ©dicament en ligne

  2. WilsonVah表示:

    pharmacie en ligne pas cher: Tadalafil sans ordonnance en ligne – pharmacie en ligne france fiable

  3. Richardprurf表示:

    https://viagrameilleurprix.shop/# Viagra vente libre pays
    pharmacie en ligne sans ordonnance

  4. WilsonVah表示:

    Sildenafil teva 100 mg sans ordonnance: Viagra pharmacie – Acheter Sildenafil 100mg sans ordonnance

  5. Perryzoozy表示:

    pharmacie en ligne pas cher pharmacie en ligne pas cher trouver un mГ©dicament en pharmacie

  6. WilsonVah表示:

    Pharmacie sans ordonnance: Pharmacies en ligne certifiees – pharmacie en ligne france pas cher

  7. U888表示:

    Youre so cool! I dont suppose Ive read something like this before. So good to find anyone with some authentic thoughts on this subject. realy thanks for beginning this up. this website is something that is wanted on the web, someone with just a little originality. useful job for bringing one thing new to the web!

  8. Jacobbep表示:

    pharmacie en ligne sans ordonnance https://pharmaciemeilleurprix.com/# Achat mГ©dicament en ligne fiable

  9. If you find that your symptoms are considerably impacting your each day life or inflicting distress, it could also be beneficial to hunt skilled assist.

  10. Richardprurf表示:

    https://tadalafilmeilleurprix.com/# pharmacie en ligne sans ordonnance
    pharmacie en ligne avec ordonnance

  11. Richardprurf表示:

    https://viagrameilleurprix.com/# Acheter viagra en ligne livraison 24h
    pharmacie en ligne france fiable

  12. WilsonVah表示:

    vente de mГ©dicament en ligne: pharmacie en ligne france pas cher – vente de mГ©dicament en ligne

  13. Hi88表示:

    There are some fascinating time limits on this article but I don?t know if I see all of them middle to heart. There is some validity however I will take hold opinion until I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as nicely

  14. NorbertKep表示:

    pharmacie en ligne fiable: kamagra livraison 24h – trouver un mГ©dicament en pharmacie

  15. U888表示:

    I enjoy what you guys are up too. This kind of clever work and coverage! Keep up the awesome works guys I’ve included you guys to blogroll.

  16. U888表示:

    Thanks for the good writeup. It in fact was once a enjoyment account it. Glance complicated to far introduced agreeable from you! However, how can we keep in touch?

  17. Richardprurf表示:

    http://pharmaciemeilleurprix.com/# pharmacie en ligne france livraison internationale
    pharmacie en ligne livraison europe

  18. NorbertKep表示:

    pharmacie en ligne fiable: pharmacie en ligne pas cher – vente de mГ©dicament en ligne

  19. U888表示:

    What?s Happening i’m new to this, I stumbled upon this I have found It positively useful and it has aided me out loads. I hope to contribute & aid other customers like its helped me. Great job.

  20. Richardprurf表示:

    https://pharmaciemeilleurprix.shop/# pharmacie en ligne sans ordonnance
    pharmacie en ligne sans ordonnance

  21. Hi88表示:

    What?s Happening i am new to this, I stumbled upon this I’ve found It absolutely useful and it has aided me out loads. I hope to contribute & assist other users like its aided me. Good job.

  22. Jacobbep表示:

    Pharmacie sans ordonnance https://pharmaciemeilleurprix.shop/# pharmacie en ligne livraison europe

  23. The second day travels alongside the river flats of the Poulter earlier than climbing by the beech forest to the Binser saddle and then descending to the carpark near the Andrews shelter in the Mt White road.

  24. 789bet表示:

    Thanks , I have recently been looking for info about this subject for ages and yours is the best I have discovered till now. But, what about the conclusion? Are you sure about the source?

  25. Jacobbep表示:

    Achat mГ©dicament en ligne fiable https://kamagrameilleurprix.shop/# pharmacie en ligne france livraison internationale

  26. NorbertKep表示:

    Prix du Viagra 100mg en France: acheter du viagra – Viagra gГ©nГ©rique sans ordonnance en pharmacie

  27. WilsonVah表示:

    pharmacie en ligne avec ordonnance: pharmacie en ligne pas cher – pharmacie en ligne

  28. WilsonVah表示:

    Viagra femme ou trouver: acheter du viagra – Viagra femme ou trouver

  29. WW88表示:

    A person necessarily lend a hand to make severely articles I might state. That is the first time I frequented your web page and so far? I surprised with the analysis you made to create this particular publish incredible. Great activity!

  30. U888表示:

    A further issue is that video games are normally serious as the name indicated with the primary focus on understanding rather than entertainment. Although, it comes with an entertainment feature to keep your young ones engaged, just about every game is normally designed to focus on a specific skill set or curriculum, such as numbers or research. Thanks for your publication.

發佈留言

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