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

37,329 Responses

  1. Win79表示:

    F*ckin? tremendous issues here. I am very happy to peer your post. Thanks a lot and i am looking forward to contact you. Will you please drop me a mail?

  2. WalterIcort表示:

    https://expressrxcanada.shop/# canadian pharmacy online

  3. alo789表示:

    Thank you for any other excellent post. Where else may anyone get that type of info in such a perfect means of writing? I’ve a presentation next week, and I am at the look for such information.

  4. Dannytal表示:

    RxExpressMexico: mexico pharmacy order online – mexico pharmacy order online

  5. gvui表示:

    I just couldn’t go away your web site before suggesting that I extremely enjoyed the standard information a person provide on your guests? Is gonna be again often to investigate cross-check new posts

  6. MichaelLoapy表示:

    indian pharmacy indian pharmacy Medicine From India

  7. gvui表示:

    Your house is valueble for me. Thanks!?

  8. MichaelLoapy表示:

    indian pharmacy online shopping pharmacy website india MedicineFromIndia

  9. Win79表示:

    I’m really impressed with your writing abilities and also with the format in your blog. Is that this a paid theme or did you modify it your self? Anyway keep up the nice high quality writing, it?s rare to see a nice blog like this one today..

  10. View details表示:

    Great work! This is the type of info that should be shared around the net. Shame on the search engines for not positioning this post higher! Come on over and visit my website . Thanks =)

  11. gvui表示:

    Heya i am for the first time here. I came across this board and I find It really useful & it helped me out a lot. I hope to give something back and help others like you helped me.

  12. Michaelrom表示:

    indian pharmacy: MedicineFromIndia – Medicine From India

  13. gvui表示:

    I?d should verify with you here. Which isn’t one thing I normally do! I take pleasure in studying a put up that may make people think. Additionally, thanks for permitting me to comment!

  14. StevenDuase表示:

    RxExpressMexico: mexico pharmacies prescription drugs – Rx Express Mexico

  15. StevenDuase表示:

    Medicine From India: Medicine From India – Medicine From India

  16. Win79表示:

    Howdy I am so delighted I found your site, I really found you by error, while I was browsing on Digg for something else, Nonetheless I am here now and would just like to say many thanks for a remarkable post and a all round enjoyable blog (I also love the theme/design), I don’t have time to look over it all at the moment but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the superb work.

  17. Win79表示:

    Hey there! Someone in my Facebook group shared this website with us so I came to give it a look. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Superb blog and terrific design and style.

  18. StevenDuase表示:

    mexico drug stores pharmacies: mexico drug stores pharmacies – mexico pharmacy order online

  19. WalterIcort表示:

    http://rxexpressmexico.com/# п»їbest mexican online pharmacies

  20. Michaelrom表示:

    canadian pharmacy tampa: ExpressRxCanada – canada drugs online

  21. Win79表示:

    Thanks for your write-up on this web site. From my own experience, periodically softening upward a photograph could possibly provide the photo shooter with a bit of an creative flare. Many times however, that soft clouds isn’t what exactly you had in mind and can frequently spoil an otherwise good photo, especially if you thinking about enlarging that.

  22. MichaelLoapy表示:

    RxExpressMexico mexico pharmacy order online mexican rx online

  23. Win79表示:

    My brother recommended I may like this website. He was once entirely right. This put up truly made my day. You can not imagine simply how a lot time I had spent for this info! Thanks!

  24. Dannytal表示:

    Medicine From India: Medicine From India – Medicine From India

  25. Индивидуальный пошив штор, закажите..
    Пошив штор для вашего дома, по доступным ценам..
    Эксклюзивные решения в пошиве штор, по индивидуальному проекту..
    Дизайнерские шторы на заказ, обратитесь к нам..
    Пошив штор с доставкой, по вашим требованиям..
    Лучшие ткани для пошива штор, по выгодным ценам..
    Пошив штор по индивидуальному заказу, Позвольте нам помочь..
    Пошив штор на заказ, вам под силу..
    Пошив штор из эксклюзивных тканей, для элитных интерьеров..
    Выберите качественный пошив штор, звоните прямо сейчас..
    Пошив штор высокого качества, по вашему дизайну..
    Пошив штор на заказ по вашим размерам, с бесплатной доставкой..
    Индивидуальный стиль ваших окон, от профессионалов..
    Индивидуальный дизайн штор, от ведущих дизайнеров..
    Эксклюзивный дизайн штор, с современными технологиями..
    Высокое качество и стиль, с гарантией долговечности..
    Пошив штор по вашим пожеланиям, по оптимальной цене..
    пошив штор пошив штор . Ткацкий

  26. Explore表示:

    Good day! This is kind of off topic but I need some help from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about setting up my own but I’m not sure where to start. Do you have any points or suggestions? With thanks

  27. Michaelrom表示:

    mexico pharmacy order online: mexico pharmacies prescription drugs – mexican online pharmacy

  28. Dozawtus表示:

    аккаунты с балансом покупка аккаунтов

  29. WalterIcort表示:

    http://rxexpressmexico.com/# RxExpressMexico

發佈回覆給「Michaelrom」的留言 取消回覆

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