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

  1. Update your wardrobe with Marc Jacobs from the marc jacobs factory outlet online.

  2. Jogue no cassino de maior prestigio Blaze

  3. Seu destino para grandes premios Blaze

  4. One important thing is that when you are searching for a education loan you may find that you will want a co-signer. There are many cases where this is true because you might discover that you do not employ a past credit history so the mortgage lender will require that you’ve someone cosign the credit for you. Good post.

  5. Hello! I’ve been following your site for some time now and finally got the bravery to go ahead and give you a shout out from Austin Tx! Just wanted to mention keep up the fantastic work!

  6. Audio began playing any time I opened this site, so annoying!

  7. Wow, wonderful blog format! How lengthy have you ever been running a blog for? you make running a blog look easy. The entire glance of your site is fantastic, let alone the content!

  8. Cassino com as melhores promocoes Blaze

  9. Descubra o melhor casino Blaze

  10. There are actually a whole lot of particulars like that to take into consideration. That is a nice point to bring up. I offer the thoughts above as normal inspiration however clearly there are questions just like the one you convey up where crucial thing can be working in honest good faith. I don?t know if finest practices have emerged around things like that, however I am sure that your job is clearly identified as a fair game. Both girls and boys really feel the impact of just a moment?s pleasure, for the rest of their lives.

  11. Diplom_rusr表示:

    купить диплом в тольятти vm-tver.ru .

  12. F*ckin? amazing things here. I?m very glad to see your article. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a e-mail?

  13. Diplom_dssr表示:

    купить диплом парикмахера http://www.vm-tver.ru/ .

  14. Shaneevige表示:

    I got this website from my buddy who informed me regarding this website and now this time I am visiting this website and reading very informative posts at this time.

    yenko.net/forum/member.php?tab=visitor_messaging&u=70162 
    gamesfortop.ru/diplomyi-na-zakaz-vash-shans-na-novuyu-kareru 
    newfinbiz.ru/page/13 
    autogroupe.ru/page/10 
    lolipopnews.ru/page/9 

  15. This website online can be a walk-via for all of the data you wanted about this and didn?t know who to ask. Glimpse right here, and also you?ll positively uncover it.

  16. Have you ever considered about including a little bit more than just your articles? I mean, what you say is important and all. However just imagine if you added some great photos or video clips to give your posts more, “pop”! Your content is excellent but with pics and clips, this site could certainly be one of the best in its field. Good blog!

  17. I take pleasure in, cause I discovered just what I was looking for. You have ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

  18. Diplom_hgsr表示:

    купить диплом в пятигорске http://vm-tver.ru/ .

  19. I have recently started a website, the information you provide on this website has helped me tremendously. Thanks for all of your time & work.

  20. A person necessarily help to make significantly articles I might state. That is the very first time I frequented your web page and so far? I surprised with the analysis you made to make this particular post extraordinary. Great process!

  21. Many thanks for this article. I’d also like to mention that it can become hard if you find yourself in school and starting out to establish a long credit rating. There are many scholars who are simply just trying to survive and have a good or good credit history can occasionally be a difficult factor to have.

  22. O cassino dos seus sonhos Blaze

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

  24. Hi, i think that i noticed you visited my web site thus i came to ?return the choose?.I’m trying to to find things to enhance my web site!I suppose its adequate to make use of a few of your ideas!!

  25. Hello there, just turned into alert to your blog via Google, and found that it is really informative. I?m gonna be careful for brussels. I will appreciate in case you continue this in future. Many folks will be benefited out of your writing. Cheers!

  26. Hi! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Thanks!

  27. O melhor casino online Blaze

  28. Desfrute dos jogos no melhor cassino Blaze

  29. Great ? I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs and related info ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your customer to communicate. Nice task..

  30. Shaneevige表示:

    Можете купить грифы для гантелей на https://grify-dlya-gantely.ru по доступным ценамнужной длины. В создании надежных снарядов применяются надежные марки металла. Гантельные элементы создаются в трех востребованных диаметрах. Снаряды предназначены для тяжелых занятий и выполнены с разметкой и насечками для надежного хвата. Продукты покрываются защитным слоем хрома и никеля. Российская фирма создает достойный ассортимент спортивного оборудования для квартиры и фитнес клуба. Это многофункциональный инвентарь для силовых тренировок в любых условиях.

發佈留言

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