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

  1. 91club.game表示:

    excellent post, very informative. I wonder why the other experts of this sector do not notice this. You should continue your writing. I’m confident, you have a huge readers’ base already!

  2. 91 club lotto表示:

    Hey there, You’ve done an incredible job. I will certainly digg it and personally recommend to my friends. I’m confident they’ll be benefited from this site.

  3. 91club.in表示:

    I was recommended this web site by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my problem. You’re amazing! Thanks!

  4. Real_jgon表示:

    Секреты успешного получения лицензии на недвижимость|Ключевая информация о лицензии на недвижимость|Подробное руководство по получению лицензии на недвижимость|Советы по получению лицензии на недвижимость|Инструкция по получению лицензии на недвижимость|Следуйте этим шагам для получения лицензии на недвижимость|Простой путь к получению лицензии на недвижимость|Как стать агентом с лицензией на недвижимость|Эффективные стратегии получения лицензии на недвижимость|Лицензия на недвижимость для начинающих: советы и рекомендации|Секреты профессиональной лицензии на недвижимость|Как получить лицензию на недвижимость и стать успешным агентом|Основные шаги к успешной лицензии на недвижимость|Как стать агентом по недвижимости с лицензией: пошаговое руководство|Советы по получению лицензии на недвижимость от профессионалов|Разберитесь в процессе получения лицензии на недвижимость: полное руководство|Шаги к успешной лицензии на недвижимость|Советы по успешному получению лицензии на недвижимость|Лицензия на недвижимость: ключ к успеху в индустрии недвижимости|Три шага к успешной лицензии на недвижимость|Получите лицензию на недвижимость и станьте профессиональным агентом|Секреты успешного получения лицензии на недвижимость|Получение лицензии на недвижимость для начинающих: советы от экспертов|Простой путь к получению лицензии на недвижимость|Эффективные советы по успешному получению лицензии на недвижимость|Лицензия на недвижимость: важные аспекты для успешного получения
    How to get my real estate license in Georgia https://realestatelicensehefrsgl.com/states/georgia-real-estate-license/ .

  5. 91 club lotto表示:

    Thanks for another wonderful article. Where else could anybody get that type of information in such a perfect way of writing? I’ve a presentation next week, and I am on the look for such info.

  6. 91 login表示:

    Thanks for this glorious article. One other thing is that most digital cameras are available equipped with any zoom lens that allows more or less of any scene to generally be included by simply ‘zooming’ in and out. All these changes in {focus|focusing|concentration|target|the a**** length tend to be reflected from the viewfinder and on massive display screen at the back of the camera.

  7. 91 club app表示:

    Hello, i feel that i noticed you visited my website so i got here to ?return the want?.I’m attempting to to find things to enhance my site!I guess its good enough to make use of a few of your concepts!!

  8. Hello! I’ve been following your web site for a while now and finally got the courage to go ahead and give you a shout out from Kingwood Texas! Just wanted to tell you keep up the fantastic work!

  9. The very root of your writing whilst appearing agreeable in the beginning, did not settle perfectly with me after some time. Someplace within the sentences you managed to make me a believer unfortunately only for a while. I still have a problem with your jumps in logic and one might do well to fill in all those gaps. When you actually can accomplish that, I could certainly end up being fascinated.

  10. 91 club game表示:

    There’s noticeably a bundle to know about this. I assume you made sure nice factors in features also.

  11. Hello There. I found your blog using msn. This is an extremely well written article. I?ll make sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will certainly comeback.

  12. new platform表示:

    You should take part in a contest for probably the greatest blogs on the web. I will advocate this website!

  13. I am curious to find out what blog system you have been using? I’m having some small security problems with my latest blog and I would like to find something more safe. Do you have any suggestions?

  14. Thanks for revealing your ideas in this article. The other factor is that every time a problem appears with a laptop or computer motherboard, people today should not take the risk involving repairing the item themselves for if it is not done right it can lead to irreparable damage to the full laptop. It’s usually safe to approach the dealer of the laptop for any repair of its motherboard. They have technicians who have an skills in dealing with pc motherboard challenges and can get the right prognosis and execute repairs.

  15. best app表示:

    I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back down the road. Cheers

  16. Hey this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding expertise so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

  17. I’ve learned newer and more effective things as a result of your weblog. One other thing I would like to say is that newer computer system operating systems usually allow more memory to use, but they as well demand more memory space simply to work. If one’s computer can’t handle additional memory plus the newest software program requires that memory space increase, it may be the time to buy a new PC. Thanks

  18. 91 lottery表示:

    Great ? I should certainly pronounce, impressed with your web site. I had no trouble navigating through all the tabs and related information 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, web site theme . a tones way for your customer to communicate. Nice task..

  19. 91clubin.in表示:

    This is the fitting weblog for anybody who needs to seek out out about this topic. You understand so much its nearly onerous to argue with you (not that I truly would need?HaHa). You definitely put a new spin on a subject thats been written about for years. Nice stuff, just great!

  20. Hiya, I’m really glad I’ve found this info. Nowadays bloggers publish just about gossips and internet and this is really annoying. A good web site with exciting content, that is what I need. Thanks for keeping this website, I’ll be visiting it. Do you do newsletters? Cant find it.

  21. I believe that is one of the so much important information for me. And i am satisfied studying your article. However wanna observation on some common issues, The web site style is perfect, the articles is truly nice : D. Just right job, cheers

  22. Thanks for the sensible critique. Me & my neighbor were just preparing to do some research about this. We got a grab a book from our area library but I think I learned more clear from this post. I’m very glad to see such excellent information being shared freely out there.

  23. 91 club表示:

    Wonderful beat ! I wish to apprentice at the same time as you amend your site, how could i subscribe for a blog web site? The account aided me a acceptable deal. I have been tiny bit familiar of this your broadcast offered shiny clear idea

  24. I can’t express how much I value the effort the author has put into writing this exceptional piece of content. The clarity of the writing, the depth of analysis, and the wealth of information offered are simply astonishing. His passion for the subject is obvious, and it has undoubtedly resonated with me. Thank you, author, for providing your insights and enriching our lives with this exceptional article!

  25. Thanks a lot for sharing this with all of us you actually know what you are talking about! Bookmarked. Please also visit my web site =). We could have a link exchange agreement between us!

  26. What i do not realize is actually how you are not actually much more well-liked than you might be right now. You are so intelligent. You realize thus significantly relating to this subject, produced me personally consider it from a lot of varied angles. Its like men and women aren’t fascinated unless it?s one thing to do with Lady gaga! Your own stuffs great. Always maintain it up!

  27. Thanks for your post. I also think that laptop computers are getting to be more and more popular lately, and now are sometimes the only sort of computer utilised in a household. This is due to the fact that at the same time that they are becoming more and more very affordable, their processing power keeps growing to the point where they may be as strong as pc’s out of just a few years back.

  28. 91 club login表示:

    You made some decent factors there. I looked on the web for the difficulty and found most individuals will go together with together with your website.

  29. 91 club login表示:

    Hiya very nice web site!! Man .. Excellent .. Amazing .. I’ll bookmark your web site and take the feeds additionally?I’m happy to find numerous helpful info here within the put up, we’d like work out more strategies on this regard, thank you for sharing. . . . . .

  30. 91clubin.in表示:

    I was suggested this web site by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my problem. You’re incredible! Thanks!

發佈留言

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