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

  1. mysgame表示:

    Hello! Would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would really enjoy your content. Please let me know. Cheers

  2. mysgame表示:

    Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is excellent, as well as the content!

  3. mysgame表示:

    Thanks for your write-up. Another thing is that being photographer consists of not only difficulties in taking award-winning photographs and also hardships in acquiring the best dslr camera suited to your requirements and most especially challenges in maintaining the caliber of your camera. This is very correct and visible for those photography enthusiasts that are into capturing the particular nature’s exciting scenes — the mountains, the particular forests, the particular wild and the seas. Going to these daring places undoubtedly requires a digicam that can live up to the wild’s hard setting.

  4. Cazrpxs表示:

    Здравствуйте!
    Мы готовы предложить документы техникумов, расположенных на территории всей России. Можно заказать диплом от любого заведения, за любой год, указав необходимую специальность и оценки за все дисциплины. Дипломы и аттестаты выпускаются на “правильной” бумаге высшего качества. Это позволяет делать государственные дипломы, не отличимые от оригиналов. Они будут заверены всеми требуемыми печатями и подписями.
    sonnick84.pointblog.net/%D0%9A%D0%B0%D0%BA-%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE-%D0%B1%D1%8B%D1%81%D1%82%D1%80%D0%BE-%D0%BA%D1%83%D0%BF%D0%B8%D1%82%D1%8C-%D0%B4%D0%B8%D0%BF%D0%BB%D0%BE%D0%BC-%D0%B2-%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD-%D0%BC%D0%B0%D0%B3%D0%B0%D0%B7%D0%B8%D0%BD%D0%B5-69472426

  5. mysgame表示:

    Admiring the time and energy you put into your blog and detailed information you provide. It’s good to come across a blog every once in a while that isn’t the same old rehashed material. Wonderful read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  6. mysgame表示:

    Hello there, I discovered your site via Google even as searching for a similar topic, your site came up, it looks great. I have bookmarked it in my google bookmarks.

  7. Xazrgup表示:

    Добрый день!
    Заказать диплом о высшем образовании
    landik-diploms-srednee.ru/attestat-shkoly В 
    Удачи!

  8. Edwardwhava表示:

    http://foruspharma.com/# mexican online pharmacies prescription drugs

  9. mysgame表示:

    you are really a good webmaster. The website loading pace is incredible. It seems that you’re doing any distinctive trick. Moreover, The contents are masterwork. you have performed a fantastic process in this matter!

  10. mysgame表示:

    Woah! I’m really loving the template/theme of this blog. It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between user friendliness and appearance. I must say you’ve done a awesome job with this. Also, the blog loads very quick for me on Opera. Outstanding Blog!

  11. CharlesDom表示:

    mexico drug stores pharmacies mexican pharmacy п»їbest mexican online pharmacies

  12. mysgame表示:

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

  13. Dnrtusa表示:

    Привет, друзья!
    Купить документ института можно в нашей компании в столице.
    ast-diplomy.com/kupit-diplom-vracha
    Хорошей учебы!

  14. mysgame表示:

    Thanks for your posting. One other thing is always that individual American states have their particular laws that affect home owners, which makes it extremely tough for the our lawmakers to come up with a different set of rules concerning property foreclosure on householders. The problem is that each state has got own guidelines which may interact in an adverse manner in relation to foreclosure guidelines.

  15. mysgame表示:

    I think this is among the most important information for me. And i’m glad reading your article. But wanna remark on some general things, The web site style is wonderful, the articles is really excellent : D. Good job, cheers

  16. CharlesDom表示:

    best online pharmacies in mexico mexican mail order pharmacies best online pharmacies in mexico

  17. Edwardwhava表示:

    https://canadapharmast.online/# canadian neighbor pharmacy

  18. Xazrten表示:

    Добрый день!
    Заказать диплом о высшем образовании
    landik-diploms-srednee.ru/svidetelstvo-o-razvode В 
    Успешной учебы!

  19. Cazrgch表示:

    Здравствуйте!
    Мы можем предложить документы техникумов, расположенных в любом регионе РФ. Можно заказать качественный диплом за любой год, включая сюда документы СССР. Дипломы и аттестаты выпускаются на “правильной” бумаге самого высокого качества. Это позволяет делать настоящие дипломы, не отличимые от оригиналов. Они будут заверены необходимыми печатями и подписями.
    forum-rassvet-rp.ru/index.php?app=gallery&module=gallery&controller=view&id=25

  20. Xazrdti表示:

    Привет!
    Предлагаем документы ВУЗов, расположенных на территории всей России. Можно купить диплом за любой год, в том числе документы старого образца СССР. Документы печатаются на “правильной” бумаге самого высшего качества. Это позволяет делать государственные дипломы, не отличимые от оригинала. Документы будут заверены необходимыми печатями и штампами.
    Мы изготавливаем дипломы психологов, юристов, экономистов и других профессий по выгодным ценам. Цена может зависеть от выбранной специальности, года выпуска и образовательного учреждения. Стараемся поддерживать для заказчиков адекватную ценовую политику. Важно, чтобы дипломы были доступны для большинства граждан.
    landik-diploms-srednee.ru/kupit-diplom-v-novosibirske В 
    Успешной учебы!

  21. Dnrtyrq表示:

    Здравствуйте!
    Купить документ института вы имеете возможность у нас.
    ast-diploms.com/kupit-diplom-voronezh
    Удачи!

  22. Рекомендую всем оригинальный сайт – Minecraft

  23. CharlesDom表示:

    mexican drugstore online medication from mexico pharmacy mexican pharmacy

  24. En iyi promosyonlara sahip casinolar Sweet bonanza

  25. En iyi cevrimici kumarhaneyi kesfedin Sweet bonanza

  26. Manrsie表示:

    Добрый день!
    Где заказать диплом по актуальной специальности?
    Мы можем предложить документы институтов, расположенных в любом регионе РФ. Вы сможете купить качественно напечатанный диплом от любого высшего учебного заведения, за любой год, включая документы СССР. Дипломы печатаются на “правильной” бумаге высшего качества. Это дает возможность делать государственные дипломы, не отличимые от оригиналов. Они заверяются всеми требуемыми печатями и штампами.
    Мы готовы предложить дипломы психологов, юристов, экономистов и прочих профессий по приятным ценам.
    diplomasx24.ru/kupit-diplom-rostov-na-donu
    Рады оказать помощь!

  27. Cazrcij表示:

    Здравствуйте!
    Мы предлагаем документы ВУЗов, расположенных в любом регионе Российской Федерации. Можно приобрести диплом за любой год, в том числе документы старого образца. Документы выпускаются на “правильной” бумаге высшего качества. Это дает возможность делать настоящие дипломы, не отличимые от оригинала. Документы будут заверены необходимыми печатями и штампами.
    wkzxrbk5k.bloggazzo.com/27843055/%D0%9A%D0%B0%D0%BA-%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE-%D0%B1%D1%83%D0%B4%D0%B5%D1%82-%D0%B1%D1%8B%D1%81%D1%82%D1%80%D0%BE-%D0%B7%D0%B0%D0%BA%D0%B0%D0%B7%D0%B0%D1%82%D1%8C-%D0%B4%D0%B8%D0%BF%D0%BB%D0%BE%D0%BC-%D0%B2-%D0%BC%D0%B0%D0%B3%D0%B0%D0%B7%D0%B8%D0%BD%D0%B5

發佈留言

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