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

  1. WilsonVah表示:

    Pharmacie en ligne livraison Europe: kamagra gel – vente de mГ©dicament en ligne

  2. Jacobbep表示:

    vente de mГ©dicament en ligne http://viagrameilleurprix.com/# SildГ©nafil 100 mg prix en pharmacie en France

  3. Yesterday, while I was at work, my sister stole my iphone and tested to see if it can survive a 25 foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone!

  4. We specialise in these, in addition to restored military timepieces, fancy enameled examples, ladies cocktail watches and examples of Deco and Artwork Nouveau wrist-artwork.

  5. If you find yourself at your desk together with your hair in knots, Suze Orman’s white teeth blinking at you from your computer display screen and the most recent subject of cash Magazine crumpled in your palms, remember this: You do not must make the “proper” choice.

  6. I really believe that a property foreclosures can have a major effect on the debtor’s life. House foreclosures can have a 7 to ten years negative relation to a applicant’s credit report. A new borrower who has applied for home financing or virtually any loans even, knows that your worse credit rating can be, the more tough it is to secure a decent mortgage loan. In addition, it might affect a borrower’s capacity to find a good place to lease or hire, if that results in being the alternative property solution. Great blog post.

  7. Undeniably believe that which you stated. Your favorite reason seemed to be on the web the simplest thing to be aware of. I say to you, I definitely get irked while people think about worries that they plainly do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks

  8. WilsonVah表示:

    Pharmacie sans ordonnance: Tadalafil sans ordonnance en ligne – pharmacie en ligne avec ordonnance

  9. Jacobbep表示:

    trouver un mГ©dicament en pharmacie https://viagrameilleurprix.shop/# Prix du Viagra 100mg en France

  10. Richardprurf表示:

    https://pharmaciemeilleurprix.shop/# pharmacie en ligne livraison europe
    trouver un mГ©dicament en pharmacie

  11. NorbertKep表示:

    Viagra homme prix en pharmacie sans ordonnance: viagra en ligne – Quand une femme prend du Viagra homme

  12. Richardprurf表示:

    http://tadalafilmeilleurprix.com/# Pharmacie sans ordonnance
    pharmacie en ligne france livraison internationale

  13. Richardprurf表示:

    https://tadalafilmeilleurprix.com/# pharmacie en ligne sans ordonnance
    п»їpharmacie en ligne france

  14. Hi I am so delighted I found your webpage, I really found you by error, while I was researching on Yahoo for something else, Anyhow I am here now and would just like to say kudos for a remarkable post and a all round entertaining blog (I also love the theme/design), I don’t have time to browse it all at the minute but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the excellent job.

  15. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали срочный ремонт iphone 11, можете посмотреть на сайте: ремонт iphone 11 в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  16. obviously like your web site but you need to check the spelling on quite a few of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I will definitely come back again.

  17. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт iphone 11, можете посмотреть на сайте: ремонт iphone 11
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  18. WilsonVah表示:

    Viagra sans ordonnance 24h suisse: acheter du viagra – Acheter viagra en ligne livraison 24h

  19. NorbertKep表示:

    pharmacie en ligne sans ordonnance: pharmacie en ligne sans ordonnance – п»їpharmacie en ligne france

  20. Jacobbep表示:

    Pharmacie Internationale en ligne https://viagrameilleurprix.com/# Viagra vente libre allemagne

  21. Eltonkep表示:

    сайт кракен отзывы – kraken зеркало, сайт кракен отзывы

  22. Jacobbep表示:

    Pharmacie Internationale en ligne http://viagrameilleurprix.com/# Viagra vente libre allemagne

  23. NorbertKep表示:

    pharmacies en ligne certifiГ©es: pharmacie en ligne france – pharmacies en ligne certifiГ©es

  24. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт iphone 11 адреса, можете посмотреть на сайте: ремонт iphone 11 в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  25. I believe that avoiding refined foods is the first step so that you can lose weight. They can taste good, but packaged foods have very little vitamins and minerals, making you try to eat more to have enough power to get with the day. In case you are constantly feeding on these foods, transferring to whole grains and other complex carbohydrates will make you to have more vitality while having less. Thanks alot : ) for your blog post.

  26. Perryzoozy表示:

    Viagra homme prix en pharmacie sans ordonnance Acheter Viagra Cialis sans ordonnance SildГ©nafil 100 mg sans ordonnance

  27. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт iphone 11 цены, можете посмотреть на сайте: срочный ремонт iphone 11
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  28. whoah this blog is magnificent i love reading your posts. Keep up the good work! You know, many people are hunting around for this information, you could help them greatly.

  29. Checking online shops could be finest, because you wouldn’t have pesky gross sales folks forcing you to buy what your small business would not need.

  30. WilsonVah表示:

    trouver un mГ©dicament en pharmacie: Pharmacie Internationale en ligne – pharmacie en ligne france livraison internationale

發佈留言

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