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

  1. WONDERFUL Post.thanks for share..extra wait .. ?

  2. wonderful put up, very informative. I ponder why the opposite experts of this sector do not notice this. You should proceed your writing. I am sure, you have a great readers’ base already!

  3. DouglasGed表示:

    cheap ed medication: cheap ed pills online – ed pills for sale

  4. I?d need to verify with you here. Which is not one thing I usually do! I get pleasure from reading a put up that may make people think. Also, thanks for allowing me to remark!

  5. DouglasGed表示:

    mexican mail order pharmacies: Best pharmacy in Mexico – п»їbest mexican online pharmacies

  6. One important issue is that when you find yourself searching for a education loan you may find that you will need a co-signer. There are many situations where this is true because you should find that you do not possess a past credit history so the bank will require that you’ve someone cosign the money for you. Good post.

  7. Charleshon表示:

    https://indiapharmacy.shop/# online pharmacy india
    ed meds on line

  8. DouglasGed表示:

    п»їlegitimate online pharmacies india: Online India pharmacy – indianpharmacy com

  9. I would like to thnkx for the efforts you’ve put in writing this blog. I am hoping the same high-grade website post from you in the upcoming also. Actually your creative writing abilities has encouraged me to get my own web site now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

  10. maymuay xxx表示:

    Heya i?m for the primary time here. I came across this board and I find It truly useful & it helped me out much. I’m hoping to present one thing again and aid others like you aided me.

  11. great put up, very informative. I’m wondering why the other specialists of this sector do not notice this. You must continue your writing. I am sure, you’ve a great readers’ base already!

  12. I love your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to create my own blog and would like to find out where u got this from. thanks

  13. I’ve learned some new things through the blog post. One other thing to I have discovered is that normally, FSBO sellers may reject a person. Remember, they can prefer to never use your expert services. But if a person maintain a gradual, professional relationship, offering aid and remaining in contact for around four to five weeks, you will usually be able to win interviews. From there, a listing follows. Many thanks

  14. Leonardpar表示:

    http://mexicopharmacy.win/# mexico pharmacies prescription drugs

  15. Leonardpar表示:

    http://indiapharmacy.shop/# pharmacy website india

  16. I am usually to running a blog and i really admire your content. The article has actually peaks my interest. I am going to bookmark your site and preserve checking for brand spanking new information.

  17. Currently it looks like Expression Engine is the best blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

  18. This web page is really a stroll-through for the entire info you needed about this and didn?t know who to ask. Glimpse here, and also you?ll undoubtedly uncover it.

  19. I’m amazed by the quality of this content! The author has obviously put a great amount of effort into exploring and structuring the information. It’s refreshing to come across an article that not only provides valuable information but also keeps the readers captivated from start to finish. Hats off to him for producing such a brilliant work!

  20. Good ? I should certainly pronounce, impressed with your website. 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, site theme . a tones way for your client to communicate. Excellent task..

  21. Unquestionably believe that which you stated. Your favorite reason seemed to be on the net the simplest thing to be aware of. I say to you, I certainly get irked while people think about worries that they just do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks

  22. Charleshon表示:

    https://mexicopharmacy.win/# п»їbest mexican online pharmacies
    affordable ed medication

  23. There are some attention-grabbing closing dates in this article but I don?t know if I see all of them heart to heart. There is some validity however I’ll take maintain opinion until I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as nicely

  24. One more thing. It’s my opinion that there are a lot of travel insurance internet sites of reliable companies that allow you to enter your vacation details and obtain you the quotes. You can also purchase your international holiday insurance policy on the web by using your credit card. Everything you need to do is usually to enter all travel details and you can start to see the plans side-by-side. Only find the package that suits your financial budget and needs and then use your credit card to buy it. Travel insurance online is a good way to begin looking for a trustworthy company with regard to international travel cover. Thanks for discussing your ideas.

  25. Thanks for your posting. One other thing is the fact that individual states have their particular laws that affect house owners, which makes it quite hard for the the legislature to come up with a brand new set of recommendations concerning foreclosures on house owners. The problem is that a state provides own laws which may work in a negative manner on the subject of foreclosure guidelines.

  26. Leonardpar表示:

    http://indiapharmacy.shop/# online shopping pharmacy india

  27. Hey are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any html coding knowledge to make your own blog? Any help would be really appreciated!

  28. Charleshon表示:

    http://edpillpharmacy.store/# where can i buy erectile dysfunction pills
    cost of ed meds

  29. I have recently started a web site, the info you offer on this web site has helped me greatly. Thanks for all of your time & work.

  30. Howdy! I know this is kinda off topic however I’d figured I’d ask. Would you be interested in exchanging links or maybe guest writing a blog post or vice-versa? My blog addresses a lot of the same subjects as yours and I think we could greatly benefit from each other. If you might be interested feel free to shoot me an email. I look forward to hearing from you! Fantastic blog by the way!

發佈留言

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