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...

35,117 Responses

  1. VictorVal表示:

    olympe: olympe casino en ligne – olympe

  2. Great post! If you’re looking for a fantastic place to find short-term rentals, I highly recommend visiting https://apartmentsapart.com/ for a wide variety of apartments across the world. Find your perfect stay today!

  3. I?ve recently started a website, the info you offer on this site has helped me tremendously. Thanks for all of your time & work.

  4. I am not sure where you’re getting your info, but great topic. I needs to spend some time learning much more or understanding more. Thanks for great info I was looking for this information for my mission.

  5. Howdy would you mind letting me know which webhost you’re using? I’ve loaded your blog in 3 completely different browsers and I must say this blog loads a lot quicker then most. Can you recommend a good web hosting provider at a honest price? Kudos, I appreciate it!

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

  7. I?ve been exploring for a little bit for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this information So i?m happy to convey that I have a very good uncanny feeling I discovered just what I needed. I most certainly will make certain to don?t forget this web site and give it a glance on a constant basis.

  8. VictorVal表示:

    olympe casino avis: olympe casino en ligne – olympe casino avis

  9. Have you ever considered about adding a little bit more than just your articles? I mean, what you say is important and everything. Nevertheless just imagine if you added some great visuals or video clips to give your posts more, “pop”! Your content is excellent but with images and videos, this site could undeniably be one of the greatest in its niche. Amazing blog!

  10. Williamwhogs表示:

    olympe casino avis: olympe casino en ligne – casino olympe

  11. I am really enjoying the theme/design of your website. Do you ever run into any web browser compatibility problems? A few of my blog audience have complained about my site not operating correctly in Explorer but looks great in Opera. Do you have any tips to help fix this issue?

  12. Gregoryron表示:

    olympe casino avis: casino olympe – olympe casino en ligne

  13. Gregoryron表示:

    olympe casino cresus: olympe casino avis – olympe casino avis

  14. VictorVal表示:

    olympe casino avis: olympe casino – olympe casino en ligne

  15. Williamwhogs表示:

    olympe: casino olympe – olympe casino en ligne

  16. VictorVal表示:

    olympe: olympe casino cresus – olympe casino cresus

  17. Thanks a lot for sharing this with all of us you really know what you’re talking about! Bookmarked. Kindly also visit my site =). We could have a link exchange agreement between us!

  18. Ronaldbet表示:

    olympe olympe casino cresus

  19. Gregoryron表示:

    olympe casino en ligne: olympe casino en ligne – olympe casino avis

  20. Williamwhogs表示:

    casino olympe: olympe casino cresus – olympe

  21. Gregoryron表示:

    olympe casino cresus: olympe casino cresus – casino olympe

  22. VictorVal表示:

    olympe casino cresus: olympe casino avis – olympe

  23. Nice post. I used to be checking constantly this weblog and I’m inspired! Very helpful information specifically the ultimate phase 🙂 I take care of such info a lot. I used to be looking for this particular information for a long time. Thank you and good luck.

  24. Hey There. I found your weblog using msn. That is an extremely well written article. I?ll make sure to bookmark it and come back to read extra of your useful information. Thanks for the post. I will certainly return.

  25. VictorVal表示:

    olympe casino en ligne: olympe casino en ligne – olympe

  26. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three e-mails with the same comment. Is there any way you can remove me from that service? Many thanks!

  27. Williamwhogs表示:

    olympe casino avis: olympe – olympe casino cresus

  28. Gregoryron表示:

    olympe casino en ligne: casino olympe – olympe casino en ligne

  29. AlbertShund表示:

    https://olympecasino.pro/# casino olympe

  30. It is my belief that mesothelioma is actually the most lethal cancer. It contains unusual attributes. The more I really look at it a lot more I am convinced it does not work like a real solid tissues cancer. In the event mesothelioma is actually a rogue viral infection, therefore there is the chance for developing a vaccine and offering vaccination for asbestos open people who are really at high risk associated with developing future asbestos relevant malignancies. Thanks for discussing your ideas on this important ailment.

發佈回覆給「Victoria BC heritage sites」的留言 取消回覆

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