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...

37,408 Responses

  1. Robertfap表示:

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

  2. One thing I’d prefer to say is always that car insurance cancellation is a dreadful experience so if you’re doing the proper things as a driver you simply won’t get one. A number of people do get the notice that they’ve been officially dropped by their insurance company they then have to fight to get additional insurance after a cancellation. Inexpensive auto insurance rates are usually hard to get after having a cancellation. Having the main reasons for auto insurance termination can help motorists prevent sacrificing one of the most essential privileges offered. Thanks for the suggestions shared by your blog.

  3. obviously like your web-site however you need to test the spelling on quite a few of your posts. A number of them are rife with spelling issues and I to find it very troublesome to inform the reality nevertheless I will surely come back again.

  4. BradleyJaire表示:

    Kamagra Commander maintenant: kamagra livraison 24h – achat kamagra

  5. very nice put up, i certainly love this website, carry on it

  6. Hi there, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam feedback? If so how do you protect against it, any plugin or anything you can advise? I get so much lately it’s driving me crazy so any help is very much appreciated.

  7. You actually make it appear really easy with your presentation however I find this topic to be really something which I believe I would by no means understand. It kind of feels too complex and extremely wide for me. I’m having a look forward on your subsequent post, I?ll attempt to get the dangle of it!

  8. Robertfap表示:

    https://tadalmed.shop/# Cialis generique prix

  9. BillieLet表示:

    Kamagra Commander maintenant: achat kamagra – Kamagra Oral Jelly pas cher

  10. okmark your weblog and check again here regularly. I’m quite certain I?ll learn many new stuff right here! Good luck for the next!

  11. A person essentially help to make seriously posts I would state. This is the very first time I frequented your web page and thus far? I amazed with the research you made to make this particular publish amazing. Magnificent job!

  12. Another thing I’ve noticed is for many people, a bad credit score is the consequence of circumstances past their control. Such as they may are already saddled with an illness so they have more bills going to collections. It can be due to a employment loss or maybe the inability to do the job. Sometimes divorce or separation can send the financial situation in a downward direction. Many thanks sharing your notions on this site.

  13. BradleyJaire表示:

    achat kamagra: kamagra en ligne – Kamagra pharmacie en ligne

  14. Robertfap表示:

    https://tadalmed.shop/# Acheter Cialis

  15. Bernardshoor表示:

    п»їpharmacie en ligne france: Pharmacie en ligne France – pharmacie en ligne avec ordonnance pharmafst.com

  16. Peterclada表示:

    Acheter Cialis Tadalafil achat en ligne cialis prix tadalmed.com

  17. sbobet表示:

    Wow! I’m in awe of the author’s writing skills and capability to convey intricate concepts in a concise and concise manner. This article is a true gem that merits all the praise it can get. Thank you so much, author, for providing your expertise and offering us with such a valuable resource. I’m truly grateful!

  18. CharlieMougs表示:

    кракен официальный сайт – kraken войти, кракен войти

  19. Bernardshoor表示:

    Cialis sans ordonnance 24h: Achat Cialis en ligne fiable – Tadalafil achat en ligne tadalmed.shop

  20. BradleyJaire表示:

    Acheter Kamagra site fiable: Kamagra Commander maintenant – Kamagra Commander maintenant

  21. We are a gaggle of volunteers and starting a new scheme in our community. Your web site provided us with valuable info to paintings on. You’ve performed an impressive process and our entire group shall be thankful to you.

  22. Peterclada表示:

    Kamagra pharmacie en ligne Achetez vos kamagra medicaments Kamagra Commander maintenant

  23. Thanks , I have recently been looking for information about this topic for ages and yours is the greatest I have discovered till now. But, what about the conclusion? Are you sure about the source?

  24. Robertfap表示:

    https://tadalmed.shop/# cialis prix

  25. BradleyJaire表示:

    Kamagra Commander maintenant: kamagra livraison 24h – kamagra pas cher

  26. Bryansnake表示:

    выберите ресурсы Криптобосс

  27. Oh my goodness! a tremendous article dude. Thank you Nonetheless I’m experiencing problem with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting similar rss drawback? Anybody who knows kindly respond. Thnkx

發佈回覆給「วิธีแทงบอล SBOBET」的留言 取消回覆

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