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

  1. bad medical表示:

    Thanks for sharing superb informations. Your web-site is very cool. I’m impressed by the details that you have on this web site. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found just the information I already searched everywhere and just couldn’t come across. What a great web-site.

  2. google spam表示:

    I have witnessed that intelligent real estate agents all around you are Advertising and marketing. They are realizing that it’s more than merely placing a sign post in the front yard. It’s really pertaining to building associations with these vendors who someday will become purchasers. So, if you give your time and energy to encouraging these retailers go it alone – the “Law connected with Reciprocity” kicks in. Interesting blog post.

  3. DanielTet表示:

    order cytotec online https://lipitor.guru/# canada prescription price lipitor
    lasix furosemide 40 mg

  4. Xazrryk表示:

    Здравствуйте!
    Заказать документ о получении высшего образования.
    Мы изготавливаем дипломы любых профессий по приятным ценам.
    spravkipiter.ru
    Окажем помощь!.

  5. google spam表示:

    I have read several good stuff here. Certainly worth bookmarking for revisiting. I wonder how much effort you put to create such a great informative website.

  6. DanielTet表示:

    purchase cytotec https://lipitor.guru/# lipitor australia
    furosemide 40 mg

  7. Thanks for your article. I also feel that laptop computers are becoming more and more popular these days, and now are sometimes the only type of computer utilised in a household. The reason being at the same time actually becoming more and more reasonably priced, their computing power keeps growing to the point where they can be as strong as personal computers out of just a few in years past.

  8. bad medical表示:

    I just like the valuable info you supply for your articles. I will bookmark your blog and test once more right here frequently. I’m quite certain I?ll be told a lot of new stuff right right here! Best of luck for the next!

  9. google spam表示:

    The other day, while I was at work, my cousin stole my iphone and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views. I know this is completely off topic but I had to share it with someone!

  10. bad medical表示:

    Thank you for another wonderful article. Where else could anyone get that kind of info in such an ideal way of writing? I’ve a presentation next week, and I’m on the look for such information.

  11. Cazrdgv表示:

    Здравствуйте!
    Получить диплом ВУЗа
    telegra.ph/kupit-diplom-dvgups-08-13

  12. Sazrggb表示:

    Привет!
    Диплом магистра
    telegra.ph/kupit-diplom-tehnikuma-v-kazani-08-13

  13. google spam表示:

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

  14. You really make it seem so easy together with your presentation but I in finding this topic to be actually one thing which I believe I’d by no means understand. It seems too complicated and very vast for me. I am having a look ahead to your subsequent post, I?ll attempt to get the hold of it!

  15. Jamesric表示:

    lisinopril 25mg tablets: Buy Lisinopril 20 mg online – can you buy lisinopril online

  16. Jamesric表示:

    lipitor generic india: cheapest ace inhibitor – buy lipitor from canada

  17. Lazrcrg表示:

    Здравствуйте!
    Приобрести диплом о высшем образовании.
    leksimage.ru

  18. Jamesric表示:

    tamoxifen citrate pct: buy tamoxifen online – tamoxifen premenopausal

  19. It’s perfect time to make a few plans for the future and it’s time to be happy. I’ve read this publish and if I may I wish to recommend you few interesting issues or advice. Perhaps you can write next articles referring to this article. I wish to read more things approximately it!

  20. bad medical表示:

    Nice weblog here! Additionally your web site a lot up fast! What host are you the usage of? Can I get your affiliate link in your host? I desire my website loaded up as quickly as yours lol

  21. google spam表示:

    Unquestionably believe that which you said. Your favorite justification appeared to be on the web the easiest thing to be aware of. I say to you, I certainly get irked while people consider worries that they just do not know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks

  22. Thanks for the recommendations shared in your blog. Something else I would like to talk about is that losing weight is not supposed to be about going on a celebrity diet and trying to reduce as much weight as you’re able in a set period of time. The most effective way to shed pounds is by using it little by little and using some basic guidelines which can provide help to make the most out of your attempt to lose weight. You may recognize and already be following these tips, yet reinforcing knowledge never does any damage.

  23. bad medical表示:

    I?ll right away seize your rss as I can’t in finding your e-mail subscription hyperlink or e-newsletter service. Do you’ve any? Please let me understand in order that I may subscribe. Thanks.

  24. medical bad表示:

    Great post here. One thing I would like to say is the fact most professional domains consider the Bachelors Degree just as the entry level standard for an online education. Even though Associate Diplomas are a great way to start out, completing ones Bachelors uncovers many doors to various employment goodies, there are numerous online Bachelor Course Programs available from institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another concern is that many brick and mortar institutions offer you Online variations of their diplomas but commonly for a significantly higher price than the firms that specialize in online degree plans.

  25. medical bad表示:

    One more thing. I really believe that there are a lot of travel insurance web sites of dependable companies that let you enter your journey details and get you the rates. You can also purchase the actual international travel cover policy on the web by using the credit card. All you should do is always to enter all your travel details and you can understand the plans side-by-side. You only need to find the system that suits your financial allowance and needs and then use your credit card to buy that. Travel insurance on the web is a good way to begin looking for a trustworthy company pertaining to international holiday insurance. Thanks for giving your ideas.

  26. Thanks for sharing your ideas on this blog. In addition, a myth regarding the banking institutions intentions whenever talking about property foreclosures is that the standard bank will not getreceive my installments. There is a certain quantity of time that this bank will require payments in some places. If you are too deep within the hole, they may commonly desire that you pay the particular payment in whole. However, that doesn’t mean that they will not take any sort of payments at all. If you and the bank can have the ability to work some thing out, a foreclosure procedure may halt. However, in case you continue to skip payments beneath new plan, the foreclosure process can just pick up from where it left off.

  27. I have noticed that online degree is getting favorite because getting your college degree online has developed into a popular alternative for many people. A large number of people have certainly not had an opportunity to attend a normal college or university although seek the increased earning potential and career advancement that a Bachelor Degree provides. Still people might have a degree in one training but would want to pursue another thing they now possess an interest in.

  28. Hey there! I know this is somewhat off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!

  29. bad medical表示:

    Simply want to say your article is as amazing. The clearness for your publish is simply nice and i could suppose you are knowledgeable in this subject. Fine with your permission allow me to take hold of your RSS feed to stay updated with drawing close post. Thanks 1,000,000 and please carry on the rewarding work.

  30. Sazrmer表示:

    Добрый день!
    Заказать документ о получении высшего образования
    diablomania.ru/forum/showthread.php?p=558189#post558189 

發佈留言

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