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

15,592 Responses

  1. PatrickLef表示:

    farmacia online piГ№ conveniente: Cialis generico prezzo – farmacia online senza ricetta

  2. Edgarappow表示:

    le migliori pillole per l’erezione: viagra senza prescrizione – pillole per erezione in farmacia senza ricetta

  3. Edgarappow表示:

    cialis farmacia senza ricetta: viagra generico – cerco viagra a buon prezzo

  4. There are some interesting closing dates on this article however I don?t know if I see all of them center to heart. There is some validity however I’ll take maintain opinion until I look into it further. Good article , thanks and we would like more! Added to FeedBurner as effectively

  5. What i don’t realize is if truth be told how you’re not actually a lot more neatly-liked than you may be right now. You are so intelligent. You already know therefore significantly relating to this subject, produced me personally consider it from so many numerous angles. Its like men and women aren’t interested until it?s one thing to accomplish with Lady gaga! Your personal stuffs excellent. All the time maintain it up!

  6. Wow, fantastic blog layout! How lengthy have you been running a blog for? you make running a blog glance easy. The whole look of your site is great, as smartly as the content material!

  7. Hello there, You have done a great job. I will definitely digg it and personally recommend to my friends. I am sure they’ll be benefited from this website.

  8. ro free表示:

    I’m really enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Exceptional work!

  9. PatrickLef表示:

    farmacia online: Farmacia online migliore – Farmacia online miglior prezzo

  10. Howdy! 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?

  11. PatrickLef表示:

    viagra pfizer 25mg prezzo: viagra generico – viagra cosa serve

  12. Отличный сайт! Всем рекомендую!Тут Вы можете заказатьВинтовые сваи спб

  13. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники в уфе

  14. MichaelToP表示:

    acquistare farmaci senza ricetta BRUFEN 600 bustine prezzo farmacia online

  15. Richardral表示:

    acquisto farmaci con ricetta Farmacie online sicure farmacie online sicure

  16. Thanks for your post right here. One thing I would really like to say is always that most professional domains consider the Bachelor Degree just as the entry level requirement for an online college degree. Whilst Associate Degrees are a great way to start, completing ones Bachelors reveals many good opportunities to various professions, there are numerous online Bachelor Course Programs available via institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another issue is that many brick and mortar institutions give Online versions of their degree programs but generally for a drastically higher charge than the corporations that specialize in online degree programs.

  17. Thanks for the new stuff you have unveiled in your short article. One thing I’d like to reply to is that FSBO relationships are built as time passes. By launching yourself to owners the first saturday their FSBO will be announced, prior to a masses commence calling on Mon, you create a good relationship. By mailing them instruments, educational supplies, free reports, and forms, you become a good ally. By taking a personal curiosity about them and their problem, you create a solid link that, most of the time, pays off once the owners decide to go with an adviser they know plus trust – preferably you actually.

  18. Richardral表示:

    acquisto farmaci con ricetta BRUFEN 600 mg 30 compresse prezzo acquistare farmaci senza ricetta

  19. Kennethtub表示:

    https://tadalafilit.com/# comprare farmaci online all’estero
    farmacia online

  20. Richardral表示:

    farmacia online BRUFEN 600 bustine prezzo Farmacie online sicure

  21. Kennethtub表示:

    https://farmaciait.men/# farmacia online
    farmacia online senza ricetta

  22. You really make it seem so easy with your presentation but I find this matter to be actually something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

  23. I?ve learn some excellent stuff here. Certainly worth bookmarking for revisiting. I surprise how so much effort you place to make the sort of fantastic informative website.

  24. I just like the valuable info you provide to your articles. I?ll bookmark your weblog and take a look at again here frequently. I am reasonably certain I will be informed many new stuff proper right here! Good luck for the following!

  25. I don?t even know how I ended up here, but I thought this post was great. I do not know who you are but certainly you are going to a famous blogger if you aren’t already 😉 Cheers!

  26. One important thing is that while you are searching for a education loan you may find that you will want a cosigner. There are many situations where this is correct because you could find that you do not possess a past credit standing so the lender will require that you have someone cosign the credit for you. Good post.

  27. I adore your wordpress template, exactly where do you download it from?

  28. Great write-up, I?m regular visitor of one?s blog, maintain up the excellent operate, and It’s going to be a regular visitor for a long time.

  29. Today, while I was at work, my cousin stole my iPad and tested to see if it can survive a thirty foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is completely off topic but I had to share it with someone!

發佈留言

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