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

  1. Отличный сайт! Всем рекомендую!картина на холсте в Тюмени

  2. RobertMef表示:

    п»їbest mexican online pharmacies: п»їbest mexican online pharmacies – mexican pharmaceuticals online

  3. Attractive section of content. I just stumbled upon your weblog and in accession capital to assert that I get in fact enjoyed account your blog posts. Any way I?ll be subscribing to your augment and even I achievement you access consistently rapidly.

  4. Just wish to say your article is as astounding. The clarity in your post is simply great and i could assume you are an expert on this subject. Well with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please continue the enjoyable work.

  5. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: ремонт крупногабаритной техники в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  6. RobertMef表示:

    top 10 online pharmacy in india: india pharmacy mail order – top 10 online pharmacy in india

  7. Can I simply say what a reduction to search out someone who actually knows what theyre speaking about on the internet. You undoubtedly know easy methods to convey a problem to light and make it important. More folks have to learn this and perceive this facet of the story. I cant consider youre no more in style because you positively have the gift.

  8. ArthurKib表示:

    https://mexicopharmacy.cheap/# mexico drug stores pharmacies

  9. ArthurKib表示:

    https://mexicopharmacy.cheap/# mexican border pharmacies shipping to usa

  10. Excellent post. I was checking continuously this blog and I am impressed! Extremely useful information specifically the last part 🙂 I care for such info much. I was looking for this particular information for a very long time. Thank you and good luck.

  11. RobertMef表示:

    online pharmacy pyridium: ventolin mexican pharmacy – pharmacy in artane castle

  12. ArthurKib表示:

    https://pharmbig24.online/# publix pharmacy bactrim

  13. MauriceGueda表示:

    non prescription online pharmacy reviews: king soopers pharmacy – pharmaceutical online ordering

  14. Thanks for a marvelous posting! I really enjoyed reading it, you might be a great author.I will always bookmark your blog and definitely will come back very soon. I want to encourage you to definitely continue your great posts, have a nice morning!

  15. MauriceGueda表示:

    п»їbest mexican online pharmacies: п»їbest mexican online pharmacies – п»їbest mexican online pharmacies

  16. Josephfub表示:

    mexico drug stores pharmacies buying from online mexican pharmacy mexico drug stores pharmacies

  17. Unquestionably imagine that which you stated. Your favorite justification appeared to be at the web the easiest factor to take into accout of. I say to you, I definitely get irked whilst folks think about issues that they plainly do not recognise about. You controlled to hit the nail upon the top and outlined out the whole thing without having side-effects , folks could take a signal. Will likely be back to get more. Thank you

  18. Josephfub表示:

    mexico pharmacies prescription drugs mexican pharmaceuticals online mexican online pharmacies prescription drugs

  19. MauriceGueda表示:

    modafinil online pharmacy: generic viagra us pharmacy – complete online pharmacy

  20. RobertMef表示:

    cialis generic online pharmacy: top rx pharmacy – compare prescription prices

  21. Josephfub表示:

    online shopping pharmacy india Online medicine home delivery india pharmacy mail order

  22. RobertMef表示:

    п»їbest mexican online pharmacies: pharmacies in mexico that ship to usa – mexican border pharmacies shipping to usa

  23. I simply could not leave your website prior to suggesting that I actually enjoyed the standard information a person provide for your guests? Is gonna be again ceaselessly to check out new posts

  24. This is really interesting, You are a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your great post. Also, I’ve shared your site in my social networks!

  25. Its like you read my mind! You appear to know a lot 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 other than that, this is excellent blog. An excellent read. I’ll certainly be back.

  26. Nice post. I used to be checking constantly this weblog and I am impressed! Extremely useful info particularly the remaining phase 🙂 I maintain such information much. I was seeking this particular information for a long time. Thank you and best of luck.

  27. Hi, i feel that i noticed you visited my weblog so i got here to ?go back the prefer?.I am trying to find issues to improve my site!I suppose its adequate to make use of a few of your ideas!!

  28. RobertMef表示:

    reputable overseas online pharmacies: discount pharmacy tadalafil – trusted online pharmacy reviews

  29. Hey! 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 difficulty finding one? Thanks a lot!

  30. Cazroir表示:

    Привет!
    Заказать диплом о высшем образовании
    купить диплом в иркутске

發佈留言

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