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

36,635 Responses

  1. Amazing blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog jump out. Please let me know where you got your theme. Many thanks

  2. Hi there, I found your web site via Google while searching for a related topic, your web site came up, it looks good. I’ve bookmarked it in my google bookmarks.

  3. I?m impressed, I need to say. Actually hardly ever do I encounter a blog that?s each educative and entertaining, and let me inform you, you’ve gotten hit the nail on the head. Your thought is outstanding; the issue is one thing that not sufficient individuals are talking intelligently about. I am very comfortable that I stumbled across this in my search for one thing regarding this.

  4. At this time it sounds like BlogEngine is the top blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

  5. That is really attention-grabbing, You are a very professional blogger. I’ve joined your rss feed and stay up for in search of extra of your wonderful post. Additionally, I have shared your web site in my social networks!

  6. Please let me know if you’re looking for a article author for your blog. You have some really good articles and I think I would be a good asset. If you ever want to take some of the load off, I’d love to write some articles for your blog in exchange for a link back to mine. Please shoot me an e-mail if interested. Thank you!

  7. I?ll right away take hold of your rss feed as I can’t to find your email subscription hyperlink or e-newsletter service. Do you have any? Please allow me recognize so that I may subscribe. Thanks.

  8. VictorVal表示:

    olympe casino cresus: olympe – casino olympe

  9. I will right away clutch your rss feed as I can’t to find your e-mail subscription link or e-newsletter service. Do you have any? Please permit me know in order that I may subscribe. Thanks.

  10. Gregoryron表示:

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

  11. Magnificent web site. A lot of useful information here. I am sending it to some friends ans additionally sharing in delicious. And obviously, thanks for your effort!

  12. Greetings! I’ve been following your blog for some time now and finally got the bravery to go ahead and give you a shout out from Humble Texas! Just wanted to tell you keep up the fantastic job!

  13. Gregoryron表示:

    olympe casino avis: casino olympe – olympe

  14. VictorVal表示:

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

  15. Закажите уникальные шторы на заказ, для квартиры.
    Идеальные шторы по вашим размерам, быстро.
    Создание штор мечты, под любой стиль.
    Эксклюзивные шторы на заказ, по индивидуальному дизайну.
    Заказать шторы на заказ для спальни, с учетом модных трендов.
    Профессиональный пошив штор по вашим размерам, по вашим желанием.
    Создание штор на заказ из натуральных тканей, используя современные технологии.
    Эксклюзивные шторы на заказ, подчеркивающие вашу индивидуальность.
    Классические шторы на заказ, под любой интерьер.
    Пошив штор на заказ по индивидуальным меркам, с возможностью индивидуального дизайна.
    Креативные шторы на заказ, с гарантией качества.
    Пошив штор по индивидуальному проекту, с высоким качеством.
    Модные шторы на заказ для вашего дома, под ваш бюджет.
    Индивидуальный пошив штор на заказ, по вашему проекту.
    Пошив штор по индивидуальному дизайну, от профессиональных мастеров.
    Пошив штор на заказ с индивидуальным подходом, под любой стиль.
    сшить шторы на заказ сшить шторы на заказ . Prokarniz

  16. VictorVal表示:

    olympe casino cresus: olympe casino en ligne – olympe casino

  17. Gregoryron表示:

    olympe casino avis: olympe casino – olympe casino en ligne

  18. VictorVal表示:

    olympe casino cresus: olympe – olympe casino avis

  19. Gregoryron表示:

    casino olympe: olympe casino avis – olympe casino

  20. Gregoryron表示:

    olympe casino: casino olympe – olympe casino

  21. Prokarniz表示:

    Дизайнерские шторы на заказ
    пошив штор на заказ пошив штор на заказ .

  22. Wonderful content! For anyone searching for high-quality apartment listings, don’t miss checking out https://apartmentsapart.com/. They offer great options for both short and long stays.

  23. VictorVal表示:

    olympe casino cresus: olympe – olympe casino

  24. My partner and I absolutely love your blog and find nearly all of your post’s to be just what I’m looking for. Does one offer guest writers to write content for you? I wouldn’t mind creating a post or elaborating on a few of the subjects you write about here. Again, awesome website!

  25. Gregoryron表示:

    olympe casino cresus: olympe casino en ligne – olympe casino

  26. ремонт холодильников aeg на дому ремонт стиральных машин aeg

  27. Gregoryron表示:

    olympe casino: casino olympe – olympe

  28. VictorVal表示:

    olympe: olympe casino avis – olympe casino

發佈留言

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