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

  1. Hi there, I discovered your blog by means of Google even as searching for a comparable matter, your site got here up, it appears great. I’ve bookmarked it in my google bookmarks.

  2. Diplomi_wwEa表示:

    Здравствуйте!
    Заказать документ о получении высшего образования вы сможете у нас.
    ast-diploms.com/kupit-diplom-o-vysshem-obrazovanii

  3. WayneCoirl表示:

    medication from mexico pharmacy: mexican rx online – best online pharmacies in mexico

  4. One thing I have actually noticed is always that there are plenty of fallacies regarding the finance institutions intentions if talking about property foreclosure. One fable in particular is the fact the bank desires your house. The lender wants your money, not your house. They want the cash they loaned you together with interest. Avoiding the bank is only going to draw some sort of foreclosed final result. Thanks for your article.

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

  6. Awesome blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple tweeks would really make my blog shine. Please let me know where you got your design. Thanks a lot

  7. Nelsonbluck表示:

    mexican rx online: medication from mexico pharmacy – mexican drugstore online

  8. DominicJaw表示:

    п»їbest mexican online pharmacies: buying prescription drugs in mexico online – purple pharmacy mexico price list

  9. doofreeseries表示:

    What?s Happening i’m new to this, I stumbled upon this I’ve found It absolutely helpful and it has helped me out loads. I hope to contribute & aid other users like its aided me. Good job.

  10. zeed123th表示:

    Thank you for the good writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, how can we communicate?

  11. wonderful issues altogether, you simply gained a brand new reader. What would you suggest in regards to your publish that you made some days ago? Any certain?

  12. I can’t express how much I admire the effort the author has put into writing this outstanding piece of content. The clarity of the writing, the depth of analysis, and the wealth of information presented are simply impressive. Her zeal for the subject is apparent, and it has definitely made an impact with me. Thank you, author, for sharing your insights and enlightening our lives with this exceptional article!

  13. you may have an ideal blog here! would you like to make some invite posts on my blog?

  14. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several e-mails with the same comment. Is there any way you can remove me from that service? Thanks a lot!

  15. Arnoldten表示:

    reputable mexican pharmacies online medicine in mexico pharmacies pharmacies in mexico that ship to usa

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

  17. I believe that avoiding highly processed foods could be the first step in order to lose weight. They may taste fine, but highly processed foods include very little nutritional value, making you take more just to have enough energy to get throughout the day. In case you are constantly consuming these foods, moving over to cereals and other complex carbohydrates will make you to have more strength while ingesting less. Good blog post.

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

  19. I just added this site to my rss reader, great stuff. Can’t get enough!

  20. I was recommended this web site by my cousin. I’m no longer positive whether or not this submit is written by means of him as no one else know such specified about my trouble. You’re amazing! Thank you!

  21. Things i have continually told persons is that when looking for a good on-line electronics store, there are a few components that you have to consider. First and foremost, you should really make sure to look for a reputable plus reliable shop that has received great assessments and scores from other consumers and industry leaders. This will ensure you are getting along with a well-known store that provides good support and assistance to their patrons. Thanks for sharing your opinions on this site.

  22. I have mastered some new issues from your web site about pcs. Another thing I have always believed is that laptop computers have become a specific thing that each residence must have for several reasons. They offer convenient ways in which to organize the home, pay bills, search for information, study, listen to music and in many cases watch television shows. An innovative way to complete these tasks is to use a laptop computer. These desktops are portable ones, small, highly effective and easily transportable.

  23. Thanks for your recommendations on this blog. A single thing I would wish to say is that often purchasing gadgets items from the Internet is certainly not new. In truth, in the past decade alone, the market for online consumer electronics has grown substantially. Today, you can find practically just about any electronic gizmo and tools on the Internet, which include cameras and camcorders to computer pieces and video games consoles.

  24. Nelsonbluck表示:

    mexican rx online: mexican pharmaceuticals online – buying prescription drugs in mexico online

  25. DominicJaw表示:

    п»їbest mexican online pharmacies: mexican online pharmacies prescription drugs – buying prescription drugs in mexico online

  26. Howdy! Someone in my Myspace group shared this website with us so I came to take a look. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Superb blog and brilliant style and design.

  27. I’m extremely impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you modify it yourself? Anyway keep up the excellent quality writing, it is rare to see a great blog like this one these days..

  28. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a bit, but instead of that, this is wonderful blog. A fantastic read. I will certainly be back.

  29. I just could not depart your web site before suggesting that I really enjoyed the standard info a person provide for your visitors? Is going to be back often to check up on new posts

  30. whoah this blog is excellent i love reading your posts. Keep up the good work! You know, many people are searching around for this information, you can aid them greatly.

發佈留言

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