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

  1. StevenDuase表示:

    mexico drug stores pharmacies: Rx Express Mexico – mexican rx online

  2. StevenDuase表示:

    best canadian online pharmacy reviews: Canadian pharmacy shipping to USA – canadian pharmacy mall

  3. alo789表示:

    We would also like to say that most individuals who find themselves without having health insurance are normally students, self-employed and those that are jobless. More than half of the uninsured are really under the age of Thirty-five. They do not come to feel they are needing health insurance because they are young in addition to healthy. Their particular income is normally spent on real estate, food, plus entertainment. Many people that do go to work either complete or as a hobby are not provided insurance by their jobs so they head out without due to rising valuation on health insurance in the usa. Thanks for the ideas you talk about through this site.

  4. Read more表示:

    There’s noticeably a bundle to find out about this. I assume you made sure nice factors in features also.

  5. Dannytal表示:

    canadian king pharmacy: ExpressRxCanada – canadian pharmacy world reviews

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

  7. MichaelLoapy表示:

    MedicineFromIndia Medicine From India Medicine From India

  8. Win79表示:

    Hello! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no data backup. Do you have any methods to protect against hackers?

  9. Michaelrom表示:

    buying prescription drugs in mexico: RxExpressMexico – Rx Express Mexico

  10. alo789表示:

    It is really a nice and helpful piece of info. I?m glad that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

  11. gvui表示:

    Hello There. I found your blog the use of msn. That is a very neatly written article. I will be sure to bookmark it and come back to learn extra of your useful information. Thank you for the post. I will certainly return.

  12. We are searching for experienced people that are interested in from working their home on a part-time basis. If you want to earn $500 a day, and you don’t mind developing some short opinions up, this might be perfect opportunity for you!

  13. WalterIcort表示:

    https://expressrxcanada.shop/# best canadian pharmacy to order from

  14. Win79表示:

    whoah this blog is great i love reading your articles. Keep up the good work! You know, lots of people are hunting around for this information, you could help them greatly.

  15. Lozxstus表示:

    маркетплейс аккаунтов соцсетей заработок на аккаунтах

  16. Dannytal表示:

    mexico pharmacy order online: RxExpressMexico – mexico pharmacy order online

  17. gvui表示:

    Hi, i believe that i noticed you visited my site so i came to ?return the desire?.I’m trying to in finding issues to enhance my web site!I guess its ok to make use of some of your ideas!!

  18. Dozawtus表示:

    продать аккаунт биржа аккаунтов

  19. Lozxstus表示:

    магазин аккаунтов купить аккаунт

  20. StevenDuase表示:

    trustworthy canadian pharmacy: Canadian pharmacy shipping to USA – canadian pharmacy world reviews

  21. WalterIcort表示:

    https://medicinefromindia.com/# best india pharmacy

  22. Win79表示:

    What i do not realize is actually how you’re not actually much more neatly-preferred than you may be now. You are very intelligent. You already know therefore considerably when it comes to this topic, produced me personally consider it from so many varied angles. Its like men and women aren’t interested unless it?s one thing to accomplish with Girl gaga! Your individual stuffs nice. Always handle it up!

  23. View details表示:

    I haven?t checked in here for some time because I thought it was getting boring, but the last few posts are great quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

  24. alo789表示:

    Hi my friend! I want to say that this post is amazing, great written and come with almost all important infos. I would like to see more posts like this .

  25. Win79表示:

    I?ll right away take hold of your rss as I can’t find your email subscription hyperlink or e-newsletter service. Do you’ve any? Kindly allow me realize so that I may subscribe. Thanks.

  26. Dannytal表示:

    canadian pharmacy sarasota: ExpressRxCanada – canadian pharmacy in canada

  27. alo789表示:

    I have observed that in digital camera models, special sensors help to {focus|concentrate|maintain focus|target|a**** automatically. The particular sensors regarding some camcorders change in contrast, while others work with a beam involving infra-red (IR) light, especially in low light. Higher specs cameras from time to time use a combination of both models and could have Face Priority AF where the digital camera can ‘See’ some sort of face as you concentrate only upon that. Many thanks for sharing your opinions on this web site.

  28. alo789表示:

    Hello there, just became alert to your blog through Google, and found that it’s really informative. I am going to watch out for brussels. I will appreciate if you continue this in future. Many people will be benefited from your writing. Cheers!

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

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