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

11,430 Responses

  1. Hello my friend! I wish to say that this post is amazing, nice written and include almost all important infos. I?d like to see more posts like this.

  2. Nelsonbluck表示:

    mexico drug stores pharmacies: п»їbest mexican online pharmacies – medication from mexico pharmacy

  3. I’ve come across that nowadays, more and more people are now being attracted to digital cameras and the field of picture taking. However, to be a photographer, you must first expend so much time deciding the exact model of photographic camera to buy as well as moving store to store just so you could potentially buy the most affordable camera of the trademark you have decided to select. But it will not end there. You also have to think about whether you should purchase a digital photographic camera extended warranty. Many thanks for the good ideas I obtained from your web site.

  4. Arnoldten表示:

    pharmacies in mexico that ship to usa mexico pharmacies prescription drugs mexican border pharmacies shipping to usa

  5. Many thanks to you for sharing these wonderful blogposts. In addition, the perfect travel and medical insurance system can often relieve those worries that come with traveling abroad. A medical crisis can before long become extremely expensive and that’s guaranteed to quickly slam a financial weight on the family’s finances. Having in place the perfect travel insurance bundle prior to setting off is worth the time and effort. Cheers

  6. Excellent website. A lot of useful information here. I?m sending it to a few friends ans also sharing in delicious. And obviously, thanks for your effort!

  7. Useful info. Fortunate me I found your site by accident, and I’m surprised why this coincidence did not came about in advance! I bookmarked it.

  8. Hello! Do you use Twitter? I’d like to follow you if that would be ok. I’m undoubtedly enjoying your blog and look forward to new updates.

  9. I would like to thank you for the efforts you’ve put in writing this web site. I am hoping the same high-grade website post from you in the upcoming also. In fact your creative writing skills has inspired me to get my own site now. Actually the blogging is spreading its wings fast. Your write up is a great example of it.

  10. I was suggested this website by way of my cousin. I’m not certain whether or not this post is written through him as nobody else know such particular approximately my difficulty. You are amazing! Thank you!

  11. One thing is that often one of the most frequent incentives for utilizing your credit cards is a cash-back or even rebate present. Generally, you’ll have access to 1-5 back with various expenses. Depending on the credit cards, you may get 1 again on most buying, and 5 again on buying made using convenience stores, gasoline stations, grocery stores and ‘member merchants’.

  12. WayneCoirl表示:

    mexico drug stores pharmacies: mexican mail order pharmacies – reputable mexican pharmacies online

  13. DominicJaw表示:

    mexican drugstore online: mexican border pharmacies shipping to usa – mexican pharmaceuticals online

  14. It’s a shame you don’t have a donate button! I’d certainly donate to this superb blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to new updates and will share this blog with my Facebook group. Talk soon!

  15. Nelsonbluck表示:

    pharmacies in mexico that ship to usa: mexican drugstore online – buying prescription drugs in mexico

  16. Arnoldten表示:

    buying from online mexican pharmacy pharmacies in mexico that ship to usa buying prescription drugs in mexico online

  17. Thank you for the sensible critique. Me and my neighbor were just preparing to do a little research on this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such great information being shared freely out there.

  18. A lot of the things you state happens to be astonishingly appropriate and that makes me wonder why I hadn’t looked at this in this light previously. Your article really did switch the light on for me as far as this subject matter goes. However at this time there is 1 position I am not really too comfy with and whilst I attempt to reconcile that with the core theme of your position, allow me see just what the rest of your subscribers have to say.Nicely done.

  19. Wow, marvelous weblog structure! How lengthy have you been running a blog for? you made blogging glance easy. The entire look of your site is great, let alone the content material!

  20. Heya i am for the first time here. I found this board and I find It truly useful & it helped me out a lot. I hope to give something back and help others like you aided me.

  21. Very good blog you have here but I was curious if you knew of any message boards that cover the same topics talked about here? I’d really like to be a part of group where I can get responses from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Thank you!

  22. From my notice, shopping for electronic devices online can for sure be expensive, nonetheless there are some principles that you can use to help you get the best discounts. There are continually ways to discover discount deals that could help make one to buy the best gadgets products at the cheapest prices. Great blog post.

  23. enemy 2021表示:

    Hey there! I’ve been reading your blog for a while now and finally got the bravery to go ahead and give you a shout out from Huffman Tx! Just wanted to say keep up the excellent job!

  24. Hey would you mind stating which blog platform you’re using? I’m going to start my own blog soon but I’m having a hard time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something unique. P.S Sorry for getting off-topic but I had to ask!

  25. My partner and I absolutely love your blog and find almost all of your post’s to be what precisely I’m looking for. can you offer guest writers to write content for yourself? I wouldn’t mind creating a post or elaborating on some of the subjects you write regarding here. Again, awesome weblog!

  26. Diplomi_plEa表示:

    Добрый день!
    Приобрести документ ВУЗа вы сможете в нашем сервисе.
    ast-diploms.com/kupit-diplom-s-registraciej

  27. WayneCoirl表示:

    mexican drugstore online: buying prescription drugs in mexico – best online pharmacies in mexico

  28. I think this is among the so much vital info for me. And i am satisfied reading your article. But wanna statement on few common things, The web site style is ideal, the articles is in reality great : D. Good job, cheers

  29. This article is a refreshing change! The author’s unique perspective and insightful analysis have made this a truly fascinating read. I’m appreciative for the effort she has put into crafting such an informative and thought-provoking piece. Thank you, author, for sharing your wisdom and igniting meaningful discussions through your exceptional writing!

發佈留言

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