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

33,524 Responses

  1. You might also scoop up the food with any bread that is served.

  2. Hiya, I’m really glad I have found this information. Nowadays bloggers publish just about gossips and web and this is really frustrating. A good site with exciting content, that is what I need. Thank you for keeping this site, I’ll be visiting it. Do you do newsletters? Can’t find it.

  3. 누누티비表示:

    Out of my observation, shopping for electronics online can for sure be expensive, nonetheless there are some tips and tricks that you can use to help you get the best discounts. There are always ways to come across discount discounts that could make one to come across the best gadgets products at the smallest prices. Great blog post.

  4. 누누티비表示:

    Hi there, simply was aware of your weblog through Google, and found that it’s really informative. I?m going to watch out for brussels. I will be grateful if you proceed this in future. Lots of other folks will likely be benefited from your writing. Cheers!

  5. 누누티비表示:

    Can I just say what a aid to search out somebody who actually is aware of what theyre talking about on the internet. You undoubtedly know learn how to deliver a problem to light and make it important. Extra individuals need to learn this and perceive this facet of the story. I cant believe youre no more widespread since you definitely have the gift.

  6. pdacenter.ru – сервис по ремонту бытовой техники
    Ремонт кофемашин в Иркутске в официальном сервисном центре PDACENTER.
    Наши инженеры выполняют ремонт любой сложности по дотупным ценам!

  7. Excellent read, I just passed this onto a colleague who was doing some research on that. And he just bought me lunch as I found it for him smile Therefore let me rephrase that: Thanks for lunch!

  8. 누누티비表示:

    I would also like to add that if you do not actually have an insurance policy or else you do not remain in any group insurance, you may well benefit from seeking the help of a health insurance agent. Self-employed or people with medical conditions generally seek the help of the health insurance agent. Thanks for your article.

  9. Montebeera表示:

    online pharmacy india online medicine shopping in india online pharmacy india

  10. 누누티비表示:

    Thanks for the concepts you have provided here. On top of that, I believe usually there are some factors which will keep your insurance premium straight down. One is, to take into consideration buying motors that are inside the good list of car insurance providers. Cars that happen to be expensive will be more at risk of being lost. Aside from that insurance coverage is also based on the value of your vehicle, so the more costly it is, then higher the particular premium you only pay.

  11. It is actually a great and useful piece of information. I am satisfied that you simply shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.

  12. 누누티비表示:

    whoah this weblog is fantastic i like studying your articles. Keep up the good paintings! You know, lots of people are searching around for this information, you could help them greatly.

  13. Williszew表示:

    https://mexicanpharminter.com/# buying from online mexican pharmacy

  14. banshee 350表示:

    I?ll right away grab your rss feed as I can not find your e-mail subscription link or newsletter service. Do you have any? Please let me know in order that I could subscribe. Thanks.

  15. JamesGag表示:

    canadapharmacyonline legit: fda approved canadian online pharmacies – canadian pharmacy cheap

  16. 누누티비表示:

    Today, I went to the beach front with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is entirely off topic but I had to tell someone!

  17. Williszew表示:

    http://mexicanpharminter.com/# Mexican Pharm International

  18. Arthurhow表示:

    https://mexicanpharminter.com/# buying from online mexican pharmacy
    canadianpharmacymeds com

  19. 누누티비表示:

    A few things i have observed in terms of computer memory is always that there are specs such as SDRAM, DDR and the like, that must match the technical specs of the motherboard. If the personal computer’s motherboard is reasonably current and there are no os issues, upgrading the ram literally takes under an hour. It’s one of several easiest laptop or computer upgrade techniques one can visualize. Thanks for sharing your ideas.

  20. Montebeera表示:

    cheapest online pharmacy india online medicine shopping in india order medicines online india

  21. Arthurhow表示:

    https://mexicanpharminter.com/# buying from online mexican pharmacy
    canada drugs online review

  22. 누누티비表示:

    I haven?t checked in here for a while because I thought it was getting boring, but the last few posts are great quality so I guess I?ll add you back to my daily bloglist. You deserve it my friend 🙂

  23. 누누티비表示:

    I know this if off topic but I’m looking into starting my own blog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100 certain. Any tips or advice would be greatly appreciated. Many thanks

  24. Following the trail blazed by the Rivera get together, and less burdened by livestock, the Portol脿 get together moved somewhat sooner.

  25. 누누티비表示:

    These days of austerity along with relative anxiousness about running into debt, most people balk against the idea of having a credit card in order to make purchase of merchandise or perhaps pay for a vacation, preferring, instead to rely on a tried in addition to trusted method of making payment – cash. However, if you’ve got the cash there to make the purchase entirely, then, paradoxically, that is the best time just to be able to use the cards for several reasons.

  26. Montebeera表示:

    cheapest pharmacy canada fda approved canadian online pharmacies canadian drug stores

發佈留言

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