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

  1. Great write-up, I am normal visitor of one?s site, maintain up the nice operate, and It is going to be a regular visitor for a long time.

  2. bokep jilbab表示:

    Youre so cool! I dont suppose Ive learn anything like this before. So nice to search out someone with some original thoughts on this subject. realy thank you for beginning this up. this website is something that is needed on the web, someone with a bit originality. useful job for bringing something new to the web!

  3. F*ckin? tremendous things here. I am very glad to see your post. Thanks so much and i’m having a look forward to contact you. Will you please drop me a mail?

  4. I appreciate, cause I found exactly what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye

  5. pure cbd oil表示:

    From my notice, shopping for consumer electronics online may be easily expensive, yet there are some how-to’s that you can use to help you get the best things. There are often ways to locate discount promotions that could make one to possess the best electronics products at the lowest prices. Thanks for your blog post.

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

  7. Thanks for your write-up. One other thing is when you are marketing your property by yourself, one of the challenges you need to be aware of upfront is when to deal with property inspection accounts. As a FSBO home owner, the key about successfully switching your property as well as saving money upon real estate agent revenue is knowledge. The more you are aware of, the softer your property sales effort might be. One area where by this is particularly essential is inspection reports.

  8. Hi, Neat post. There is a problem with your web site in internet explorer, would test this? IE still is the market leader and a good portion of people will miss your fantastic writing because of this problem.

  9. pure cbd oil表示:

    Hey! I could have sworn I’ve been to this website before but after reading through some of the post I realized it’s new to me. Nonetheless, I’m definitely glad I found it and I’ll be book-marking and checking back frequently!

  10. cbd massage表示:

    Good post. I study one thing more difficult on completely different blogs everyday. It would always be stimulating to learn content from different writers and observe slightly something from their store. I?d favor to make use of some with the content material on my blog whether or not you don?t mind. Natually I?ll give you a hyperlink on your internet blog. Thanks for sharing.

  11. Hey there just wanted to give you a quick heads up. The words in your post seem to be running off the screen in Internet explorer. I’m not sure if this is a format issue or something to do with browser compatibility but I figured I’d post to let you know. The layout look great though! Hope you get the issue solved soon. Thanks

  12. Howdy! This is kind of off topic but I need some advice from an established blog. Is it very difficult to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about creating my own but I’m not sure where to start. Do you have any tips or suggestions? Many thanks

  13. I?m not sure where you are getting your info, but great topic. I needs to spend some time learning more or understanding more. Thanks for great info I was looking for this information for my mission.

  14. cbd massage表示:

    Do you mind if I quote a few of your articles as long as I provide credit and sources back to your site? My blog is in the very same niche as yours and my users would certainly benefit from some of the information you provide here. Please let me know if this alright with you. Cheers!

  15. Today, taking into consideration the fast chosen lifestyle that everyone leads, credit cards get this amazing demand throughout the market. Persons throughout every discipline are using credit card and people who not using the credit card have prepared to apply for 1. Thanks for spreading your ideas in credit cards.

  16. Tynhrr表示:

    rumalaya online order – cheap generic shallaki how to get endep without a prescription

  17. cbd massage表示:

    This webpage does not render correctly on my iphone4 – you may want to try and fix that

  18. Oh my goodness! an amazing article dude. Thank you Nevertheless I am experiencing challenge with ur rss . Don?t know why Unable to subscribe to it. Is there anybody getting identical rss drawback? Anybody who is aware of kindly respond. Thnkx

  19. Another thing is that while searching for a good internet electronics retail outlet, look for web stores that are continually updated, keeping up-to-date with the hottest products, the top deals, in addition to helpful information on goods and services. This will ensure you are doing business with a shop that really stays over the competition and provide you what you ought to make educated, well-informed electronics purchases. Thanks for the important tips I have learned through your blog.

  20. Do you have a spam problem on this blog; I also am a blogger, and I was wanting to know your situation; many of us have developed some nice practices and we are looking to exchange solutions with other folks, be sure to shoot me an email if interested.

  21. bokep jilbab表示:

    Generally I do not read post on blogs, but I would like to say that this write-up very forced me to try and do it! Your writing style has been amazed me. Thanks, very nice article.

  22. I feel this is one of the most significant information for me. And i am happy reading your article. However should commentary on few general things, The site style is ideal, the articles is really great : D. Just right job, cheers

  23. obviously like your web site but you have to check the spelling on quite a few of your posts. Many of them are rife with spelling issues and I to find it very bothersome to tell the reality however I?ll certainly come again again.

  24. okmark your blog and check again here frequently. I’m quite certain I will learn a lot of new stuff right here! Good luck for the next!

  25. Drstobeese表示:

    wellbutrin sr online pharmacy: can i buy viagra at pharmacy – lloyd pharmacy viagra

  26. Drstobeese表示:

    humana pharmacy login: best pharmacy to buy provigil – apollo pharmacy online

  27. JeffreyPlaiz表示:

    https://pharm24on.com/# tylenol 3 pharmacy name
    thailand pharmacy online

  28. bokep jilbab表示:

    I?d must examine with you here. Which isn’t one thing I usually do! I get pleasure from studying a submit that can make individuals think. Also, thanks for allowing me to comment!

  29. JeffreyPlaiz表示:

    https://onlineph24.com/# british pharmacy viagra
    viagra us pharmacy online

發佈留言

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