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

  1. I love what you guys are usually up too. Such clever work and reporting! Keep up the terrific works guys I’ve included you guys to blogroll.

  2. I can’t believe how amazing this article is! The author has done a phenomenal job of conveying the information in an engaging and enlightening manner. I can’t thank him enough for offering such precious insights that have certainly enlightened my knowledge in this subject area. Hats off to him for creating such a work of art!

  3. medical bad表示:

    Thanks for your posting. One other thing is individual states have their unique laws that affect home owners, which makes it extremely tough for the Congress to come up with a different set of rules concerning home foreclosure on house owners. The problem is that every state has got own regulations which may have impact in an unwanted manner in terms of foreclosure insurance plans.

  4. bad medical表示:

    I’m not sure why but this website is loading extremely slow for me. Is anyone else having this issue or is it a issue on my end? I’ll check back later and see if the problem still exists.

  5. Hmm it appears like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to the whole thing. Do you have any recommendations for rookie blog writers? I’d genuinely appreciate it.

  6. What?s Going down i am new to this, I stumbled upon this I have discovered It absolutely useful and it has helped me out loads. I hope to contribute & aid different customers like its helped me. Great job.

  7. Another thing is that when looking for a good on-line electronics store, look for online shops that are consistently updated, always keeping up-to-date with the most current products, the most beneficial deals, in addition to helpful information on products. This will ensure that you are doing business with a shop which stays ahead of the competition and offers you things to make knowledgeable, well-informed electronics buys. Thanks for the crucial tips I have learned through your blog.

  8. Spot on with this write-up, I truly assume this web site wants much more consideration. I?ll probably be once more to read way more, thanks for that info.

  9. medical bad表示:

    Thank you for every other excellent article. Where else may just anyone get that kind of info in such a perfect way of writing? I have a presentation subsequent week, and I am at the search for such information.

  10. Hi there just wanted to give you a quick heads up. The words in your article 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 thought I’d post to let you know. The design look great though! Hope you get the problem resolved soon. Thanks

  11. Some opportunity funds also will invest in securitized or non-securitized public or private debt instruments, with the objective of privatizing, repackaging, restructuring and then selling off these interests.

  12. DanielTet表示:

    Cytotec 200mcg price http://lipitor.guru/# lipitor 80 mg
    furosemida 40 mg

  13. Hi there! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  14. I’ve been surfing online more than 3 hours these days, but I by no means found any interesting article like yours. It is lovely price sufficient for me. In my opinion, if all webmasters and bloggers made excellent content material as you probably did, the internet will probably be much more helpful than ever before.

  15. google spam表示:

    It’s a shame you don’t have a donate button! I’d most certainly donate to this superb blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this blog with my Facebook group. Talk soon!

  16. DanielTet表示:

    buy misoprostol over the counter http://lisinopril.guru/# purchase lisinopril
    lasix side effects

  17. medical bad表示:

    I like the helpful information you provide in your articles. I will bookmark your weblog and check again here regularly. I’m quite certain I?ll learn lots of new stuff right here! Good luck for the next!

  18. Whoa! This blog looks exactly like my old one! It’s on a completely different topic but it has pretty much the same layout and design. Wonderful choice of colors!

  19. You have it, you just don’t realize it.

  20. I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a developer to create your theme? Fantastic work!

  21. By the 2000s, CME had expanded to offer four core financial instruments: commodities, foreign exchange, interest rates, and stock indexes.

  22. google spam表示:

    I?ll immediately grab your rss as I can’t find your email subscription link or e-newsletter service. Do you have any? Please let me know in order that I could subscribe. Thanks.

  23. I?ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to make such a wonderful informative web site.

  24. What?s Happening i’m new to this, I stumbled upon this I have discovered It positively helpful and it has aided me out loads. I hope to contribute & aid other customers like its helped me. Good job.

  25. Today, I went to the beachfront with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

  26. Hello there, just become alert to your blog through Google, and located that it’s really informative. I?m gonna watch out for brussels. I?ll be grateful when you continue this in future. Lots of other people might be benefited from your writing. Cheers!

  27. Those who aren’t currently enrolled in school can earn up to 12 undergraduate credits from Colorado State University’s Department of Natural Resources, Recreation and Tourism.

  28. Normally I do not read post on blogs, however I wish to say that this write-up very pressured me to take a look at and do so! Your writing style has been surprised me. Thank you, very great post.

  29. bad medical表示:

    I believe that avoiding packaged foods is the first step to lose weight. They might taste great, but highly processed foods contain very little nutritional value, making you take in more in order to have enough vitality to get throughout the day. Should you be constantly taking in these foods, transferring to whole grain products and other complex carbohydrates will help you to have more strength while taking in less. Good blog post.

發佈留言

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