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

13,933 Responses

  1. One thing I’d like to say is the fact that car insurance canceling is a feared experience and if you are doing the best things being a driver you simply will not get one. A number of people do are sent the notice that they are officially dumped by their particular insurance company they have to struggle to get further insurance after a cancellation. Affordable auto insurance rates usually are hard to get after a cancellation. Having the main reasons for auto insurance cancellation can help individuals prevent sacrificing one of the most crucial privileges out there. Thanks for the thoughts shared by means of your blog.

  2. Can I simply say what a aid to seek out someone who truly is aware of what theyre talking about on the internet. You undoubtedly know how you can carry a difficulty to mild and make it important. More people need to learn this and understand this facet of the story. I cant imagine youre no more common because you positively have the gift.

  3. fantastic post, very informative. I wonder why the other specialists of this sector do not notice this. You should continue your writing. I am sure, you have a great readers’ base already!

  4. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a little bit, but instead of that, this is wonderful blog. A great read. I will certainly be back.

  5. Wow! I’m in awe of the author’s writing skills and talent to convey complex concepts in a clear and precise manner. This article is a true gem that merits all the accolades it can get. Thank you so much, author, for providing your knowledge and offering us with such a priceless resource. I’m truly thankful!

  6. WayneCoirl表示:

    pharmacies in mexico that ship to usa: mexican mail order pharmacies – mexican border pharmacies shipping to usa

  7. Hi, Neat post. There is a problem with your site in internet explorer, would check this? IE still is the market leader and a large portion of people will miss your fantastic writing due to this problem.

  8. One thing is that one of the most common incentives for making use of your credit card is a cash-back as well as rebate supply. Generally, you’re going to get 1-5 back upon various purchases. Depending on the card, you may get 1 returning on most acquisitions, and 5 back again on acquisitions made going to convenience stores, gasoline stations, grocery stores plus ‘member merchants’.

  9. DominicJaw表示:

    best online pharmacies in mexico: buying from online mexican pharmacy – mexico drug stores pharmacies

  10. I’m really enjoying the theme/design of your website. Do you ever run into any web browser compatibility issues? A couple of my blog audience have complained about my blog not operating correctly in Explorer but looks great in Chrome. Do you have any suggestions to help fix this problem?

  11. Lazrmmf表示:

    Привет, друзья!
    Мы изготавливаем дипломы любой профессии по приятным тарифам.
    traquegarden.com/купить-диплом-пгупс

  12. Thanks for your suggestions. One thing we have noticed is the fact that banks and also financial institutions have in mind the spending behavior of consumers and as well understand that plenty of people max away their cards around the breaks. They properly take advantage of this real fact and commence flooding ones inbox and also snail-mail box having hundreds of no interest APR credit card offers shortly after the holiday season concludes. Knowing that for anyone who is like 98 in the American open public, you’ll soar at the opportunity to consolidate personal credit card debt and move balances to 0 rate credit cards.

  13. One thing I have actually noticed is the fact that there are plenty of fallacies regarding the banking companies intentions whenever talking about foreclosure. One delusion in particular is the fact that the bank would like your house. The financial institution wants your money, not your property. They want the funds they lent you with interest. Averting the bank will simply draw a new foreclosed final result. Thanks for your article.

  14. Nelsonbluck表示:

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

  15. I really like your wordpress theme, wherever would you down load it from?

  16. I have read several good stuff here. Definitely worth bookmarking for revisiting. I wonder how so much attempt you put to create this sort of excellent informative website.

  17. Hello my loved one! I wish to say that this post is awesome, great written and include approximately all vital infos. I would like to look extra posts like this .

  18. Arnoldten表示:

    mexico pharmacies prescription drugs pharmacies in mexico that ship to usa mexico drug stores pharmacies

  19. Hello! 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 Humble Tx! Just wanted to mention keep up the good job!

  20. A person essentially help to make seriously posts I would state. This is the very first time I frequented your web page and thus far? I surprised with the research you made to make this particular publish extraordinary. Great job!

  21. My coder is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using WordPress on a variety of websites for about a year and am concerned about switching to another platform. I have heard great things about blogengine.net. Is there a way I can import all my wordpress posts into it? Any help would be really appreciated!

  22. WayneCoirl表示:

    purple pharmacy mexico price list: mexican drugstore online – purple pharmacy mexico price list

  23. DominicJaw表示:

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

  24. hello there and thank you for your info ? I?ve definitely picked up something new from right here. I did however expertise some technical points using this site, since I experienced to reload the website a lot of times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I’m complaining, but sluggish loading instances times will very frequently affect your placement in google and can damage your quality score if advertising and marketing with Adwords. Anyway I am adding this RSS to my email and can look out for a lot more of your respective intriguing content. Make sure you update this again very soon..

  25. Thanks for the sensible critique. Me & my neighbor were just preparing to do a little research about this. We got a grab a book from our local library but I think I learned more clear from this post. I am very glad to see such fantastic information being shared freely out there.

  26. I am so happy to read this. This is the type of manual that needs to be given and not the accidental misinformation that’s at the other blogs. Appreciate your sharing this best doc.

  27. I additionally believe that mesothelioma cancer is a rare form of cancer that is often found in people previously familiar with asbestos. Cancerous tissues form inside the mesothelium, which is a protective lining which covers a lot of the body’s bodily organs. These cells generally form inside lining on the lungs, abdominal area, or the sac which encircles one’s heart. Thanks for expressing your ideas.

發佈留言

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