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

10,413 Responses

  1. MauriceGueda表示:

    medicine in mexico pharmacies: medication from mexico pharmacy – buying from online mexican pharmacy

  2. MauriceGueda表示:

    medicine in mexico pharmacies: mexican mail order pharmacies – mexico drug stores pharmacies

  3. ArthurKib表示:

    http://indianpharmacy.company/# top online pharmacy india

  4. ArthurKib表示:

    https://mexicopharmacy.cheap/# mexican pharmaceuticals online

  5. RobertMef表示:

    pharmacies in mexico that ship to usa: pharmacies in mexico that ship to usa – mexican pharmaceuticals online

  6. Josephfub表示:

    pharmacy viagra now boots pharmacy xenical can you use target pharmacy rewards online

  7. Josephfub表示:

    mexico drug stores pharmacies mexican pharmaceuticals online buying prescription drugs in mexico online

  8. Josephfub表示:

    best online pharmacy india online pharmacy india buy medicines online in india

  9. RobertMef表示:

    top online pharmacy india: indianpharmacy com – Online medicine order

  10. Thanks for the auspicious writeup. It in reality used to be a entertainment account it. Look advanced to more brought agreeable from you! However, how could we communicate?

  11. I do love the manner in which you have presented this issue plus it does indeed present me personally a lot of fodder for thought. Nonetheless, coming from what I have seen, I really wish as other commentary stack on that individuals remain on issue and not embark on a soap box regarding the news of the day. Anyway, thank you for this exceptional piece and whilst I can not necessarily agree with it in totality, I regard the viewpoint.

  12. Hi there! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!

  13. ArthurKib表示:

    https://indianpharmacy.company/# best india pharmacy

  14. Amazing blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple adjustements would really make my blog jump out. Please let me know where you got your design. Many thanks

  15. I take pleasure in, cause I found exactly what I was having a look for. You have ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye

  16. Thank you, I’ve just been looking for information approximately this topic for a long time and yours is the greatest I have discovered so far. However, what about the bottom line? Are you positive in regards to the source?

  17. It is the best time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions. Maybe you could write next articles referring to this article. I wish to read even more things about it!

  18. Отличный сайт! Всем рекомендую!слив курсов.net

  19. Thanks a lot for the helpful posting. It is also my opinion that mesothelioma has an particularly long latency period of time, which means that signs and symptoms of the disease may well not emerge until finally 30 to 50 years after the 1st exposure to asbestos. Pleural mesothelioma, that is certainly the most common form and influences the area about the lungs, could cause shortness of breath, upper body pains, and a persistent coughing, which may bring on coughing up maintain.

  20. Many thanks for this article. I would also like to talk about the fact that it can always be hard if you find yourself in school and starting out to initiate a long credit score. There are many scholars who are just simply trying to endure and have a long or good credit history can sometimes be a difficult factor to have.

  21. Hello, i think that i saw you visited my web site so i came to ?return the favor?.I am attempting to find things to enhance my site!I suppose its ok to use some of your ideas!!

  22. Heya this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding expertise so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!

  23. I loved as much as you will obtain carried out proper here. The comic strip is tasteful, your authored subject matter stylish. nonetheless, you command get got an edginess over that you want be delivering the following. unwell undoubtedly come more before once more as exactly the same just about a lot steadily within case you shield this hike.

  24. Thanks for these tips. One thing I should also believe is the fact that credit cards featuring a 0 apr often lure consumers in with zero monthly interest, instant approval and easy over-the-internet balance transfers, however beware of the most recognized factor that may void your current 0 easy street annual percentage rate and also throw one out into the bad house quickly.

  25. Can I just say what a reduction to search out somebody who truly is aware of what theyre talking about on the internet. You definitely know the right way to carry an issue to gentle and make it important. Extra folks need to learn this and perceive this side of the story. I cant consider youre no more fashionable since you undoubtedly have the gift.

  26. I have been surfing online more than three hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my view, if all web owners and bloggers made good content as you did, the web will be a lot more useful than ever before.

  27. I am really inspired together with your writing skills as well as with the structure in your blog. Is this a paid theme or did you modify it your self? Anyway keep up the excellent quality writing, it?s uncommon to peer a great blog like this one these days..

  28. Wonderful work! This is the type of info that should be shared around the web. Shame on Google for not positioning this post higher! Come on over and visit my web site . Thanks =)

  29. Based on my observation, after a in foreclosure home is sold at an auction, it is common for your borrower to be able to still have some sort ofthat remaining unpaid debt on the financial loan. There are many lenders who try and have all fees and liens cleared by the following buyer. Even so, depending on specific programs, laws, and state regulations there may be some loans which aren’t easily fixed through the switch of financial products. Therefore, the responsibility still rests on the debtor that has had his or her property in foreclosure. Thank you for sharing your thinking on this web site.

  30. Hello! I’ve been following your site for a long time now and finally got the bravery to go ahead and give you a shout out from Austin Texas! Just wanted to tell you keep up the great work!

發佈留言

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