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

3,676 Responses

  1. Отличный Консалтинговый центр! Всем рекомендую!гражданство Молдовы по рождению представляет собой 15-летний опыт юристов собранный в едином центре услуг. Наша миссия – предоставить возможность любому гражданину оформить гражданство Молдовы и Румынии в соответствии с законодательными нормами страны.

  2. Отличный Консалтинговый центр! Всем рекомендую!гражданство Румынии представляет собой 15-летний опыт юристов собранный в едином центре услуг. Наша миссия – предоставить возможность любому гражданину оформить гражданство Молдовы и Румынии в соответствии с законодательными нормами страны.

  3. Отличный Консалтинговый центр! Всем рекомендую!гражданство Молдовы представляет собой 15-летний опыт юристов собранный в едином центре услуг. Наша миссия – предоставить возможность любому гражданину оформить гражданство Молдовы и Румынии в соответствии с законодательными нормами страны.

  4. Дуже крутий сайт! Всім рекомендую! розетка

  5. Дуже крутий сайт! Всім рекомендую! hjptnrf

  6. Дуже крутий сайт! Всім рекомендую! розетка

  7. Дуже крутий сайт! Всім рекомендую! rozetka

  8. flishiz表示:

    stromectol online kaufen Side effects were more numerous and more severe in patients receiving chemotherapy with or without tamoxifen

  9. nushsoincrj表示:

    pharmacie ouverte entre midi pharmacie esplanade auchan pharmacie aix en provence place de la mairie [url=https://toolbarqueries.google.es/url?q=https://i-meet.com/groups/generique-tapentadol-prix-canada-tapentadol-prix-sans-ordonnance/group-wall/]https://www.youtube.com/redirect?q=http://www.icicemac.com/forums/topic/eszopiclone-generique-en-vente-vente-lunesta-sans-ordonnance-2/[/url] pharmacie de garde aujourd’hui en vendee .
    therapie cognitivo comportementale psychiatre [url=https://maps.google.es/url?q=https://fr.ulule.com/recherche-fr-stromectol/]https://www.youtube.com/redirect?q=https://nocompromise.house/boards/topic/705023/acheter-g%C3%A9n%C3%A9rique-lozol-canada-acheter-du-vrai-indapamide[/url] medicaments diuretiques .
    therapies analytiques [url=https://maps.google.es/url?q=https://publiclab.org/notes/print/35879]https://www.youtube.com/redirect?q=https://i-meet.com/groups/ou-acheter-du-ivermectine-stromectol-generique-en-vente/group-wall/[/url] pharmacie becker monteux horaires .
    pharmacie de garde khemisset aujourd’hui [url=https://maps.google.es/url?q=https://nocompromise.house/boards/topic/724089/florinef-livraison-canada-floricot-sans-ordonnance-canada]https://maps.google.fr/url?q=https://www.bark.com/fr/fr/company/diurin-furosemide-40-mg-achat-en-ligne-belgique/2KDQX/[/url] therapies louise guay .
    pharmacie inter beauvais [url=https://www.youtube.com/redirect?q=https://i-meet.com/groups/generique-beurises-prix-france-ou-acheter-du-furosemide/group-wall/]https://maps.google.fr/url?q=http://www.icicemac.com/forums/topic/generique-finasteride-prix-belgique-propecia-pas-cher/[/url] pharmacie centre commercial auchan issy les moulineaux , pharmacie bordeaux rue lucien faure .

  10. BpofDeLiZgt表示:

    Отличный сайт! coach сумки купить в москве рекомендую зайти на сайт и выбрать сумочку на любой вкус!

  11. BnofDeLiZgt表示:

    Отличный сайт! coach официальный интернет магазин рекомендую зайти на сайт и выбрать сумочку на любой вкус!

  12. flishiz表示:

    stromectol tablets buy online The oral DHT Inhibitors are a class of compounds that inhibit the conversion of testosterone to DHT

  13. flishiz表示:

    buy ivermectin tablets online By using the DrugBank and TTD database, we constructed a DE ceRNA drug network Fig

  14. BLMfDeLiZgt表示:

    Отличный сайт! сумка coach рекомендую зайти на сайт и выбрать сумочку на любой вкус!

  15. AABAKAWLBIXox表示:

    can i get generic aripiprazole [url=https://aripiprazolelife.online/]can i purchase cheap aripiprazole without prescription[/url] can you get generic aripiprazole

  16. flishiz表示:

    and blood pressure readings stromectol

  17. flishiz表示:

    If your looking for an anti e that doesnt hinder gains, go with Arimidex or liquidex throughout cycle still have nolva on hand Now for post cycle therapy, I assume you know about the 300 100 50 split on clomid buy stromectol 3mg Although we demonstrated E2 mediated increases in cardiac output that were attenuated after nonselective ER blockade as well as selective ERО± blockade, E2 effects on RV capillarization as well as RV ERK1 2 activation were only attenuated after nonselective ER blockade, but not after ERО± or ERОІ selective blockade

  18. BLkjDeLiZgt表示:

    Отличный хирург! сойфер владимир валерьевич отзывы рекомендую зайти на сайт и ознакомиться с отзывами!

  19. OABAKAWLBIXmi表示:

    where buy generic abilify without rx [url=https://abilifylife.online/]can i buy abilify without insurance[/url] can you get cheap abilify price

  20. XsaYnndLiZgt表示:

    Тут можно узнать PURE ICE FRESH MINT безопасно и по выгодному курсу!

  1. 2022-10-21

    what should i write my paper on https://top100custompapernapkins.com/

  2. 2022-10-21

    help writing a college paper https://researchpaperswriting.org/

  3. 2022-10-21

    what are the best paper writing services https://cheapcustompaper.org/

  4. 2022-10-21
  5. 2022-10-21

    i will pay you to write my paper https://mypaperwritinghelp.com/

  6. 2022-10-21

    buying papers online https://writemypaperquick.com/

  7. 2022-10-21

    custom paper writing https://essaybuypaper.com/

  8. 2022-10-21
  9. 2022-10-21

    need someone write my paper https://premiumpapershelp.com/

  10. 2022-10-21

    paper writing service college https://ypaywallpapers.com/

發佈留言

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