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

  1. zentai表示:

    Another important part is that if you are an older person, travel insurance regarding pensioners is something you should really think about. The more mature you are, the harder at risk you’re for allowing something terrible happen to you while abroad. If you are never covered by a few comprehensive insurance plan, you could have quite a few serious problems. Thanks for discussing your advice on this blog.

  2. сервисный центре предлагает ремонт телевизоров в москве адреса – ремонт телевизоров

  3. Thanks for making me to achieve new ideas about pcs. I also have the belief that one of the best ways to keep your laptop computer in best condition has been a hard plastic-type case, or shell, which fits over the top of one’s computer. These types of protective gear will be model unique since they are made to fit perfectly above the natural outer shell. You can buy these directly from owner, or from third party sources if they are designed for your mobile computer, however its not all laptop can have a covering on the market. Once more, thanks for your guidelines.

  4. Travelers prone to foot blisters might even consider packing blister balm or blister cushions to help stop blisters from forming in the first place.

  5. Take time to check airline baggage laws so you have no unpleasant surprises while you test in (they’ve become rigorous about the scale and weight of luggage and can charge further if you happen to exceed their rules!) Once you have your bags recognized, merely work by way of the next steps to make certain you may easily convey the whole lot you’ve got chosen on your trip.

  6. They declare to have appointments available for the subsequent day however Omicron is hitting Argentina arduous and demand for tests is Excessive, I’d go ahead and reserve your test now.

  7. ArnoldDRODA表示:

    lasix tablet: buy furosemide – furosemide 100 mg

  8. Thirteen newspaper clippings concerning the merger of the Evangelical United Brethren, and the Methodist churches.

  9. 12. “Blessings, you’ve got many this morning.

  10. zentai表示:

    Thank you for the auspicious writeup. It in reality used to be a amusement account it. Glance advanced to far delivered agreeable from you! However, how could we keep up a correspondence?

  11. This is able to enable you to work occasionally or on the weekends while saving cash.

  12. JosephWrela表示:

    neurontin for sale: neurontin price comparison – generic neurontin

  13. Where can I discover one of the best UGG offers?

  14. In 1997 the club, beneath the management of Bob Both, inaugurated the Jersey Shore Relay for Particular Olympics.

  15. But there are additionally some debatable points.

  16. You may find large units which could simply store most types of stuff, as an illustration a five-foot tall storage storage starter system.

  17. zentai表示:

    I think other web site proprietors should take this site as an model, very clean and excellent user genial style and design, let alone the content. You’re an expert in this topic!

  18. Just want to say your article is as amazing. The clearness in your post is simply great and i could assume you’re an expert on this subject. Fine with your permission let me to grab your feed to keep up to date with forthcoming post. Thanks a million and please continue the rewarding work.

  19. Thanks a lot for sharing this with all of us you actually recognise what you are talking about! Bookmarked. Kindly also consult with my web site =). We can have a hyperlink trade contract among us!

  20. zentai表示:

    Definitely imagine that which you said. Your favorite justification appeared to be on the web the simplest thing to take note of. I say to you, I certainly get annoyed while other folks think about concerns that they plainly do not understand about. You controlled to hit the nail upon the top and also defined out the entire thing with no need side effect , people can take a signal. Will probably be again to get more. Thanks

  21. Сервисный центр предлагает качественный ремонт электросамокатов playshion сервис ремонта электросамокатов playshion

  22. Good ? I should certainly pronounce, impressed with your website. I had no trouble navigating through all tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your client to communicate. Nice task..

  23. zentai表示:

    One thing I have actually noticed is the fact that there are plenty of misguided beliefs regarding the banks intentions whenever talking about property foreclosure. One fable in particular is the bank would like your house. The financial institution wants your hard earned money, not your home. They want the cash they lent you together with interest. Keeping away from the bank is only going to draw a new foreclosed final result. Thanks for your posting.

  24. Edgarappow表示:

    farmacia online: Cialis generico 20 mg 8 compresse prezzo – acquisto farmaci con ricetta

  25. Throughout the grand design of things you actually get a B+ just for effort and hard work. Exactly where you misplaced me personally ended up being in your particulars. You know, it is said, details make or break the argument.. And that couldn’t be much more true right here. Having said that, let me tell you just what exactly did deliver the results. Your writing is highly powerful which is probably why I am taking an effort in order to comment. I do not make it a regular habit of doing that. Secondly, while I can certainly notice a leaps in reasoning you make, I am definitely not confident of exactly how you appear to unite your points which inturn make the conclusion. For the moment I shall subscribe to your position however hope in the near future you actually link the facts better.

  26. wonderful points altogether, you just gained a brand new reader. What would you recommend about your post that you made some days ago? Any positive?

  27. Edgarappow表示:

    comprare farmaci online all’estero: Cialis generico prezzo – Farmacia online piГ№ conveniente

  28. Профессиональный сервисный центр по ремонту компьютеров и ноутбуков в Москве.
    Мы предлагаем: ремонт macbook москва
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  29. Edgarappow表示:

    comprare farmaci online con ricetta: Cialis generico controindicazioni – acquisto farmaci con ricetta

  30. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт бытовой техники в ростове на дону
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

發佈留言

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