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

  1. thca flower表示:

    I know of the fact that currently, more and more people are being attracted to surveillance cameras and the issue of photography. However, really being a photographer, it’s important to first shell out so much time deciding the model of camera to buy and moving out of store to store just so you can buy the most economical camera of the brand you have decided to pick. But it won’t end at this time there. You also have to think about whether you can purchase a digital digital camera extended warranty. Many thanks for the good recommendations I gained from your blog site.

  2. thca flower表示:

    One thing I’d like to say is before obtaining more computer system memory, look at the machine in which it would be installed. In case the machine is running Windows XP, for instance, a memory limit is 3.25GB. Putting in above this would easily constitute some sort of waste. Make sure that one’s motherboard can handle the particular upgrade quantity, as well. Good blog post.

  3. thca flower表示:

    Good day! I know this is kind of off topic but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one? Thanks a lot!

  4. thca flower表示:

    Just desire to say your article is as astounding. The clearness for your submit is just excellent and that i can think you are an expert in this subject. Fine with your permission allow me to clutch your RSS feed to keep up to date with coming near near post. Thanks 1,000,000 and please continue the gratifying work.

  5. Matthewchact表示:

    raloxifene vs tamoxifen: tamoxifen bone density – tamoxifen rash

  6. Fantastic site. Lots of useful info here. I?m sending it to a few friends ans also sharing in delicious. And naturally, thanks for your effort!

  7. Hey! This is my first comment here so I just wanted to give a quick shout out and say I genuinely enjoy reading through your articles. Can you recommend any other blogs/websites/forums that cover the same topics? Thanks a ton!

  8. Oh my goodness! an incredible article dude. Thank you However I am experiencing subject with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting equivalent rss downside? Anybody who is aware of kindly respond. Thnkx

  9. FobertWen表示:

    Hello, I want to subscribe for this web site to take hottest updates, thus where can i do it please help.

    http://opwww.com/qzyz872/gb/?action=reply&t=qzyz872stuff&thread=20151127214853&type=gb&home=qzyz872&sort=Rr&page=4

  10. alpha hen表示:

    Thanks for your recommendations on this blog. One particular thing I would wish to say is that purchasing electronic devices items on the Internet is not new. Actually, in the past decade alone, the marketplace for online electronic devices has grown noticeably. Today, you can find practically any kind of electronic tool and gizmo on the Internet, including cameras and also camcorders to computer components and gaming consoles.

  11. vkporn表示:

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

  12. Отличный сайт! Всем рекомендую!пиастрикс казино

  13. Matthewchact表示:

    where can i buy zithromax uk: zithromax 1000 mg pills – zithromax online australia

  14. That is really interesting, You’re an excessively professional blogger. I’ve joined your feed and look ahead to looking for more of your fantastic post. Also, I’ve shared your website in my social networks!

  15. Have you ever thought about including a little bit more than just your articles? I mean, what you say is fundamental and all. However think of if you added some great visuals or video clips to give your posts more, “pop”! Your content is excellent but with images and video clips, this website could undeniably be one of the very best in its niche. Fantastic blog!

  16. imfast28表示:

    Simply want to say your article is as amazing. The clarity in your post is simply spectacular and i can assume you are an expert on this subject. Well with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please continue the gratifying work.

  17. Mazrfrd表示:

    Добрый день!
    Официальная покупка диплома вуза с упрощенной программой обучения
    rushkas-diplomasxx.ru/diplom-tekhnikuma-kolledzha

  18. Hello! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be great if you could point me in the direction of a good platform.

  19. LewisTwera表示:

    http://cytotecbestprice.pro/# buy misoprostol over the counter

  20. Hello very nice site!! Man .. Beautiful .. Amazing .. I will bookmark your web site and take the feeds also?I am satisfied to seek out a lot of helpful info here in the post, we need develop more techniques in this regard, thanks for sharing. . . . . .

  21. Trefnss表示:

    Добрый день!
    Быстрая покупка диплома старого образца: возможные риски
    diploms-man.ru/attestat-za-9-klass
    Рады оказаться полезными!.

  22. I have been absent for a while, but now I remember why I used to love this site. Thank you, I will try and check back more often. How frequently you update your website?

  23. thca flower表示:

    Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, how could we communicate?

  24. thca flower表示:

    It’s a shame you don’t have a donate button! I’d certainly donate to this outstanding blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this site with my Facebook group. Talk soon!

  25. Another thing I’ve noticed is that often for many people, a bad credit score is the reaction of circumstances above their control. Such as they may be actually saddled by having an illness and as a consequence they have substantial bills going to collections. It could be due to a job loss and the inability to go to work. Sometimes divorce process can truly send the financial situation in the wrong direction. Thanks sharing your ideas on this site.

  26. thca flower表示:

    I just could not depart your site before suggesting that I really enjoyed the usual information an individual provide for your guests? Is going to be again often to check out new posts

  27. Sogerp表示:

    generic oxcarbazepine – buy pirfenex cheap brand synthroid 150mcg

  28. thca flower表示:

    Good post. I be taught one thing more challenging on different blogs everyday. It can at all times be stimulating to learn content material from different writers and follow somewhat something from their store. I?d favor to use some with the content on my blog whether you don?t mind. Natually I?ll give you a hyperlink on your internet blog. Thanks for sharing.

  29. Nice blog right here! Additionally your site quite a bit up very fast! What host are you the use of? Can I am getting your associate hyperlink to your host? I wish my web site loaded up as fast as yours lol

  30. thca flower表示:

    hi!,I like your writing so much! share we communicate more about your article on AOL? I need a specialist on this area to solve my problem. May be that’s you! Looking forward to see you.

發佈留言

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